<template>
  <div class="linkedin-container">
    <!-- 使用封装的顶部导航组件 -->
    <MainHeader/>

    <!-- 主要内容区 -->
    <div class="main-container">
      <!-- 使用封装的侧边菜单组件 -->
      <SideMenu/>

      <!-- 右侧内容区 -->
      <div class="content">
        <!-- 搜索区域 -->
        <div class="search-container">
          <div class="search-title">{{ t('linkedin.search') }}</div>

          <!-- 搜索输入区 -->
          <div class="search-box-container">
            <el-input
                v-model="queryParams.fullName"
                :placeholder="t('linkedin.search.name')"
                clearable
                class="search-input"
                @clear="resetNameSearch"
                @input="handleNameInputChange"
                prefix-icon="el-icon-search"
            ></el-input>
          </div>
        </div>

        <!-- 主内容区域 - 左侧筛选器 + 右侧卡片列表 -->
        <div class="linkedin-main">
          <!-- 左侧筛选器，添加固定效果 -->
          <div class="filter-sidebar-container">
            <div class="filter-sidebar">
              <!-- 添加重置按钮 -->
              <div class="reset-filter-container">
                <el-button @click="resetAllFilters" class="reset-filter-btn">
                  {{ t('linkedin.reset.filters') }}
                </el-button>
              </div>

              <div class="filter-group">
                <div class="filter-header" @click="toggleFilter('companyName')">
                  <i class="filter-icon"></i>
                  <span>{{ t('linkedin.company') }}</span>
                  <i :class="['el-icon', expanded.companyName ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.companyName" class="filter-content">
                  <!-- 搜索框 -->
                  <div class="filter-search" :class="{ 'is-loading': esSearchLoading.companyName }">
                    <el-input
                        v-model="companyNameSearch"
                        :placeholder="t('linkedin.search.company')"
                        size="small"
                        clearable
                        @input="handleCompanyNameSearch"
                        prefix-icon="el-icon-search"
                    ></el-input>
                    <div class="filter-search-loading" v-if="esSearchLoading.companyName">
                      <i class="el-icon-loading"></i>
                      <span>{{ t('linkedin.filter.loading', {}, '搜索中...') }}</span>
                    </div>
                  </div>

                  <el-checkbox :indeterminate="isIndeterminate.companyName" v-model="checkAll.companyName"
                               @change="handleCheckAllChange('companyName')">{{ t('all') }}
                  </el-checkbox>
                  <el-divider></el-divider>
                  <el-checkbox-group v-model="filters.companyName" @change="handleCompanyNameItemChange">
                    <!-- 显示已选中的自定义项 -->
                    <template v-if="selectedCustomCompanyNames.length > 0">
                      <div class="es-selected-items">
                        <div v-for="item in selectedCustomCompanyNames" :key="`selected-${item}`">
                          <el-checkbox :value="item">{{ item }}</el-checkbox>
                        </div>
                      </div>
                    </template>

                    <!-- 显示筛选后的预定义选项 -->
                    <el-checkbox v-for="item in filteredCompanyNames"
                                 :key="item"
                                 :value="item">
                      {{ getCompanyNameLabel(item) }}
                    </el-checkbox>

                    <!-- 显示ES查询结果 -->
                    <template v-if="esCompanyNames.length > 0">
                      <!--                      <div class="es-result-divider">{{ t('linkedin.filter.es.results', {}, '搜索结果') }}</div>-->
                      <div v-for="item in esCompanyNames" :key="`es-${item}`">
                        <el-checkbox :value="item">{{ item }}</el-checkbox>
                      </div>
                    </template>
                  </el-checkbox-group>
                </div>
              </div>

              <div class="filter-group">
                <div class="filter-header" @click="toggleFilter('jobTitle')">
                  <i class="filter-icon"></i>
                  <span>{{ t('linkedin.job.title') }}</span>
                  <i :class="['el-icon', expanded.jobTitle ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.jobTitle" class="filter-content">
                  <!-- 搜索框 -->
                  <div class="filter-search" :class="{ 'is-loading': esSearchLoading.jobTitle }">
                    <el-input
                        v-model="jobTitleSearch"
                        :placeholder="t('linkedin.search.job')"
                        size="small"
                        clearable
                        @input="handleJobTitleSearch"
                        prefix-icon="el-icon-search"
                    ></el-input>
                    <div class="filter-search-loading" v-if="esSearchLoading.jobTitle">
                      <i class="el-icon-loading"></i>
                      <span>{{ t('linkedin.filter.loading', {}, '搜索中...') }}</span>
                    </div>
                  </div>

                  <el-checkbox :indeterminate="isIndeterminate.jobTitle" v-model="checkAll.jobTitle"
                               @change="handleCheckAllChange('jobTitle')">{{ t('all') }}
                  </el-checkbox>
                  <el-divider></el-divider>
                  <el-checkbox-group v-model="filters.jobTitle" @change="handleJobTitleItemChange">
                    <!-- 显示已选中的自定义项 -->
                    <template v-if="selectedCustomJobTitles.length > 0">
                      <div class="es-selected-items">
                        <div v-for="item in selectedCustomJobTitles" :key="`selected-${item}`">
                          <el-checkbox :value="item">{{ item }}</el-checkbox>
                        </div>
                      </div>
                    </template>

                    <!-- 显示筛选后的预定义选项 -->
                    <el-checkbox v-for="item in filteredJobTitles"
                                 :key="item"
                                 :value="item">
                      {{ getJobTitleLabel(item) }}
                    </el-checkbox>

                    <!-- 显示ES查询结果 -->
                    <template v-if="esJobTitles.length > 0">
                      <!--                      <div class="es-result-divider">{{ t('linkedin.filter.es.results', {}, '搜索结果') }}</div>-->
                      <div v-for="item in esJobTitles" :key="`es-${item}`">
                        <el-checkbox :value="item">{{ item }}</el-checkbox>
                      </div>
                    </template>
                  </el-checkbox-group>
                </div>
              </div>

              <div class="filter-group">
                <div class="filter-header" @click="toggleFilter('industry')">
                  <i class="filter-icon"></i>
                  <span>{{ t('linkedin.industry') }}</span>
                  <i :class="['el-icon', expanded.industry ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.industry" class="filter-content">
                  <!-- 搜索框 -->
                  <div class="filter-search" :class="{ 'is-loading': esSearchLoading.industry }">
                    <el-input
                        v-model="industrySearch"
                        :placeholder="t('linkedin.search.industry')"
                        size="small"
                        clearable
                        @input="handleIndustrySearch"
                        prefix-icon="el-icon-search"
                    ></el-input>
                    <div class="filter-search-loading" v-if="esSearchLoading.industry">
                      <i class="el-icon-loading"></i>
                      <span>{{ t('linkedin.filter.loading', {}, '搜索中...') }}</span>
                    </div>
                  </div>

                  <el-checkbox :indeterminate="isIndeterminate.industry" v-model="checkAll.industry"
                               @change="handleCheckAllChange('industry')">{{ t('all') }}
                  </el-checkbox>
                  <el-divider></el-divider>
                  <el-checkbox-group v-model="filters.industry" @change="handleIndustryItemChange">
                    <!-- 显示已选中的自定义项 -->
                    <template v-if="selectedCustomIndustries.length > 0">
                      <div class="es-selected-items">
                        <div v-for="item in selectedCustomIndustries" :key="`selected-${item}`">
                          <el-checkbox :value="item">{{ item }}</el-checkbox>
                        </div>
                      </div>
                    </template>

                    <!-- 显示筛选后的预定义选项 -->
                    <el-checkbox v-for="item in filteredIndustries"
                                 :key="item"
                                 :value="item">
                      {{ getIndustryLabel(item) }}
                    </el-checkbox>

                    <!-- 显示ES查询结果 -->
                    <template v-if="esIndustries.length > 0">
                      <!--                      <div class="es-result-divider">{{ t('linkedin.filter.es.results', {}, '搜索结果') }}</div>-->
                      <div v-for="item in esIndustries" :key="`es-${item}`">
                        <el-checkbox :value="item">{{ item }}</el-checkbox>
                      </div>
                    </template>
                  </el-checkbox-group>
                </div>
              </div>

              <div class="filter-group">
                <div class="filter-header" @click="toggleFilter('location')">
                  <i class="filter-icon"></i>
                  <span>{{ t('linkedin.location') }}</span>
                  <i :class="['el-icon', expanded.location ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.location" class="filter-content">
                  <!-- 搜索框 -->
                  <div class="filter-search" :class="{ 'is-loading': esSearchLoading.location }">
                    <el-input
                        v-model="locationSearch"
                        :placeholder="t('linkedin.search.location')"
                        size="small"
                        clearable
                        @input="handleLocationSearch"
                        prefix-icon="el-icon-search"
                    ></el-input>
                    <div class="filter-search-loading" v-if="esSearchLoading.location">
                      <i class="el-icon-loading"></i>
                      <span>{{ t('linkedin.filter.loading', {}, '搜索中...') }}</span>
                    </div>
                  </div>

                  <el-checkbox :indeterminate="isIndeterminate.location" v-model="checkAll.location"
                               @change="handleCheckAllChange('location')">{{ t('all') }}
                  </el-checkbox>
                  <el-divider></el-divider>
                  <el-checkbox-group v-model="filters.location" @change="handleLocationItemChange">
                    <!-- 显示已选中的自定义项 -->
                    <template v-if="selectedCustomLocations.length > 0">
                      <div class="es-selected-items">
                        <div v-for="item in selectedCustomLocations" :key="`selected-${item}`">
                          <el-checkbox :value="item">{{ item }}</el-checkbox>
                        </div>
                      </div>
                    </template>

                    <!-- 显示筛选后的预定义选项 -->
                    <el-checkbox v-for="item in filteredLocations"
                                 :key="item"
                                 :value="item">
                      {{ getLocationLabel(item) }}
                    </el-checkbox>

                    <!-- 显示ES查询结果 -->
                    <template v-if="esLocations.length > 0">
                      <!--                      <div class="es-result-divider">{{ t('linkedin.filter.es.results', {}, '搜索结果') }}</div>-->
                      <div v-for="item in esLocations" :key="`es-${item}`">
                        <el-checkbox :value="item">{{ item }}</el-checkbox>
                      </div>
                    </template>
                  </el-checkbox-group>
                </div>
              </div>


              <div class="filter-group">
                <div class="filter-header" @click="toggleFilter('contactMethod')">
                  <i class="filter-icon"></i>
                  <span>{{ t('linkedin.contact.method') }}</span>
                  <i :class="['el-icon', expanded.contactMethod ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.contactMethod" class="filter-content">
                  <el-checkbox :indeterminate="isIndeterminate.contactMethod" v-model="checkAll.contactMethod"
                               @change="handleCheckAllChange('contactMethod')">{{ t('all') }}
                  </el-checkbox>
                  <el-divider></el-divider>
                  <el-checkbox-group v-model="filters.contactMethod" @change="handleFilterChange('contactMethod')">
                    <el-checkbox :value="'email'">{{ t('email') }}</el-checkbox>
                    <el-checkbox :value="'phone'">{{ t('phone') }}</el-checkbox>
                    <el-checkbox :value="'linkedin'">{{ t('linkedin') }}</el-checkbox>
                    <el-checkbox :value="'companyWebsite'">{{ t('linkedin.url.company.website') }}</el-checkbox>
                    <el-checkbox :value="'facebookUrl'">{{ t('linkedin.url.facebook') }}</el-checkbox>
                    <el-checkbox :value="'twitterUrl'">{{ t('linkedin.url.twitter') }}</el-checkbox>
                    <el-checkbox :value="'githubUrl'">{{ t('linkedin.url.github') }}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>

              <div class="filter-group">
                <div class="filter-header" @click="toggleFilter('companySize')">
                  <i class="filter-icon"></i>
                  <span>{{ t('linkedin.company.size') }}</span>
                  <i :class="['el-icon', expanded.companySize ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="expanded.companySize" class="filter-content">
                  <el-checkbox :indeterminate="isIndeterminate.companySize" v-model="checkAll.companySize"
                               @change="handleCheckAllChange('companySize')">{{ t('all') }}
                  </el-checkbox>
                  <el-divider></el-divider>
                  <el-checkbox-group v-model="filters.companySize" @change="handleFilterChange('companySize')">
                    <el-checkbox v-for="item in companySizeOptions"
                                 :key="item"
                                 :value="item">
                      {{ getCompanySizeLabel(item) }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧数据内容 -->
          <div class="data-content">
            <!-- 操作按钮 -->
            <div class="action-bar">
              <!-- 符合条件的数量显示 -->
              <div class="matched-count">
                <span>{{ t('linkedin.matched.count') }}</span>
                <span class="matched-count-number" v-loading="countLoading">{{ formatNumber(displayedCount) }}</span>
                <!--                <span>{{ t('linkedin.matched.count.unit') }}</span>-->
              </div>
              <div>
                <el-button @click="handleExport" class="export-btn">
                  {{ t('linkedin.export.data') }}
                </el-button>
              </div>
            </div>

            <!-- 卡片式联系人列表 -->
            <div v-loading="loading" class="contact-card-list">
              <div v-for="contact in paginatedContacts" :key="contact.id" class="contact-card">
                <!-- 移除勾选框 -->

                <div class="card-content">
                  <div class="contact-header">
                    <div class="contact-name-section">
                      <div class="avatar-container">
                        <el-avatar
                            :size="50"
                            :src="contact.avatar || getRandomAvatar(contact.id, contact.fullName)"
                            class="contact-avatar"
                            @error="handleAvatarError"
                        ></el-avatar>
                      </div>
                      <div class="name-container">
                        <h3 class="contact-name">{{ formatName(contact.fullName) }}</h3>
                        <div class="country-flag-container">
                          <img
                              :src="getCountryFlag(contact.country)"
                              class="country-flag"
                              @error="handleFlagError"
                              alt=""
                          />
                          <span class="country-name">{{ formatCountryName(contact.country) }}</span>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="contact-info">
                    <!-- 未展开时显示基本信息：职位、公司和行业 -->
                    <div v-if="!contact.expanded" class="basic-info">
                      <div class="info-row" v-if="contact.jobTitle">
                        <span class="info-label">{{ t('linkedin.position') }}:</span>
                        <span class="info-value">{{ getJobTitleLabel(contact.jobTitle) }}</span>
                      </div>

                      <div class="info-row" v-if="contact.companyName">
                        <span class="info-label-compact">{{ t('linkedin.company.label') }}:</span>
                        <span class="info-value">{{ contact.companyName }}</span>
                      </div>


                      <div class="info-row" v-if="contact.industry">
                        <span class="info-label">{{ t('linkedin.industry.label') }}:</span>
                        <span class="info-value">{{ getIndustryLabel(contact.industry) }}</span>
                      </div>

                      <!-- 未展开状态下显示联系信息并添加标签 -->
                      <div v-if="contact.emails || contact.mobile">
                        <div class="info-row">
                          <span class="info-label">{{ t('linkedin.contact.info') }}:</span>
                          <div class="contact-methods-inline">
                            <div v-if="contact.emails" class="email-info">
                              <i class="el-icon-message"></i>
                              <el-tooltip
                                  v-if="contact.emails && contact.emails.includes('*')"
                                  :content="t('linkedin.view.full.contact.tooltip')"
                                  placement="top"
                                  effect="dark"
                              >
                                <span
                                    class="masked-info"
                                    @click="showFullContactInfo(contact, 'emails')">
                                  {{ contact.emails }}
                                  <el-icon class="info-lock-icon"><Lock/></el-icon>
                                </span>
                              </el-tooltip>
                              <span v-else>{{ contact.emails }}</span>
                            </div>
                            <div v-if="contact.mobile" class="phone-info">
                              <i class="el-icon-phone"></i>
                              <el-tooltip
                                  v-if="contact.mobile && contact.mobile.includes('*')"
                                  :content="t('linkedin.view.full.contact.tooltip')"
                                  placement="top"
                                  effect="dark"
                              >
                                <span
                                    class="masked-info"
                                    @click="showFullContactInfo(contact, 'mobile')">
                                  {{ formatPhoneNumber(contact.mobile) }}
                                  <el-icon class="info-lock-icon"><Lock/></el-icon>
                                </span>
                              </el-tooltip>
                              <span v-else>{{ formatPhoneNumber(contact.mobile) }}</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    <!-- 详细信息 (只在展开时显示) -->
                    <div v-if="contact.expanded" class="expanded-info">
                      <!-- 基本信息显示在详细信息上面 -->
                      <div class="basic-info-top">
                        <div class="info-row" v-if="contact.jobTitle">
                          <span class="info-label">{{ t('linkedin.position') }}:</span>
                          <span class="info-value">{{ getJobTitleLabel(contact.jobTitle) }}</span>
                        </div>

                        <div class="info-row" v-if="contact.companyName">
                          <span class="info-label-compact">{{ t('linkedin.company.label') }}:</span>
                          <span class="info-value">{{ contact.companyName }}</span>
                        </div>

                        <div class="info-row" v-if="contact.industry">
                          <span class="info-label">{{ t('linkedin.industry.label') }}:</span>
                          <span class="info-value">{{ getIndustryLabel(contact.industry) }}</span>
                        </div>

                        <!-- 展开状态下也添加联系信息标签，但显示完整信息 -->
                        <div v-if="contact.emails || contact.mobile">
                          <div class="info-row">
                            <span class="info-label">{{ t('linkedin.contact.info') }}:</span>
                            <div class="contact-methods-inline">
                              <div v-if="contact.emails" class="email-info">
                                <i class="el-icon-message"></i>
                                <el-tooltip
                                    v-if="contact.emails && contact.emails.includes('*')"
                                    :content="t('linkedin.view.full.contact.tooltip')"
                                    placement="top"
                                    effect="dark"
                                >
                                  <span
                                      class="masked-info"
                                      @click="showFullContactInfo(contact, 'emails')">
                                    {{ contact.emails }}
                                    <el-icon class="info-lock-icon"><Lock/></el-icon>
                                  </span>
                                </el-tooltip>
                                <span v-else>{{ contact.emails }}</span>
                              </div>
                              <div v-if="contact.mobile" class="phone-info">
                                <i class="el-icon-phone"></i>
                                <el-tooltip
                                    v-if="contact.mobile && contact.mobile.includes('*')"
                                    :content="t('linkedin.view.full.contact.tooltip')"
                                    placement="top"
                                    effect="dark"
                                >
                                  <span
                                      class="masked-info"
                                      @click="showFullContactInfo(contact, 'mobile')">
                                    {{ contact.mobile }}
                                    <el-icon class="info-lock-icon"><Lock/></el-icon>
                                  </span>
                                </el-tooltip>
                                <span v-else>{{ contact.mobile }}</span>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <el-divider content-position="left">{{ t('linkedin.details.info') }}</el-divider>

                      <!-- 移除已在上方显示的字段和联系方式 -->
                      <div class="info-row" v-if="contact.location && contact.location !== contact.locationCountry">
                        <span class="info-label-wide">{{ t('linkedin.location.label') }}:</span>
                        <span class="info-value">{{ getLocationLabel(contact.location) }}</span>
                      </div>

                      <div class="info-row" v-if="contact.companySize">
                        <span class="info-label-wide">{{ t('linkedin.company.size.label') }}:</span>
                        <span class="info-value">{{ getCompanySizeLabel(contact.companySize) }}</span>
                      </div>

                      <div class="info-row"
                           v-if="contact.companyIndustry && contact.companyIndustry !== contact.industry">
                        <span class="info-label-wide">{{ t('linkedin.company.industry') }}:</span>
                        <span class="info-value">{{ getIndustryLabel(contact.companyIndustry) }}</span>
                      </div>

                      <div class="info-row" v-if="contact.inferredSalary">
                        <span class="info-label-wide">{{ t('linkedin.salary.range') }}:</span>
                        <span class="info-value">{{ contact.inferredSalary }}</span>
                      </div>

                      <div class="info-row" v-if="contact.yearsExperience">
                        <span class="info-label-wide">{{ t('linkedin.work.experience') }}:</span>
                        <span class="info-value">{{ contact.yearsExperience }}{{ t('linkedin.years') }}</span>
                      </div>

                      <div class="info-row" v-if="contact.companyWebsite">
                        <span class="info-label-wide">{{ t('linkedin.company.website') }}:</span>
                        <span class="info-value">
                          <el-tooltip
                              v-if="contact.companyWebsite && contact.companyWebsite.includes('*')"
                              :content="t('linkedin.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                          >
                            <span
                                class="masked-info"
                                @click="showFullContactInfo(contact, 'companyWebsite')">
                              {{ contact.companyWebsite }}
                              <el-icon class="info-lock-icon"><Lock/></el-icon>
                            </span>
                          </el-tooltip>
                          <span v-else>{{ contact.companyWebsite }}</span>
                        </span>
                      </div>

                      <div class="info-row" v-if="contact.linkedinUrl">
                        <span class="info-label-wide">{{ t('linkedin.linkedin.url') }}:</span>
                        <span class="info-value">
                          <el-tooltip
                              v-if="contact.linkedinUrl && contact.linkedinUrl.includes('*')"
                              :content="t('linkedin.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                          >
                            <span
                                class="masked-info"
                                @click="showFullContactInfo(contact, 'linkedinUrl')">
                              {{ contact.linkedinUrl }}
                              <el-icon class="info-lock-icon"><Lock/></el-icon>
                            </span>
                          </el-tooltip>
                          <span v-else>{{ contact.linkedinUrl }}</span>
                        </span>
                      </div>

                      <div class="info-row" v-if="contact.facebookUrl">
                        <span class="info-label-wide">{{ t('linkedin.facebook.url') }}:</span>
                        <span class="info-value">
                          <el-tooltip
                              v-if="contact.facebookUrl && contact.facebookUrl.includes('*')"
                              :content="t('linkedin.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                          >
                            <span
                                class="masked-info"
                                @click="showFullContactInfo(contact, 'facebookUrl')">
                              {{ contact.facebookUrl }}
                              <el-icon class="info-lock-icon"><Lock/></el-icon>
                            </span>
                          </el-tooltip>
                          <span v-else>{{ contact.facebookUrl }}</span>
                        </span>
                      </div>

                      <div class="info-row" v-if="contact.twitterUrl">
                        <span class="info-label-wide">{{ t('linkedin.twitter.url') }}:</span>
                        <span class="info-value">
                          <el-tooltip
                              v-if="contact.twitterUrl && contact.twitterUrl.includes('*')"
                              :content="t('linkedin.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                          >
                            <span
                                class="masked-info"
                                @click="showFullContactInfo(contact, 'twitterUrl')">
                              {{ contact.twitterUrl }}
                              <el-icon class="info-lock-icon"><Lock/></el-icon>
                            </span>
                          </el-tooltip>
                          <span v-else>{{ contact.twitterUrl }}</span>
                        </span>
                      </div>

                      <div class="info-row" v-if="contact.githubUrl">
                        <span class="info-label-wide">{{ t('linkedin.github.url') }}:</span>
                        <span class="info-value">
                          <el-tooltip
                              v-if="contact.githubUrl && contact.githubUrl.includes('*')"
                              :content="t('linkedin.view.full.contact.tooltip')"
                              placement="top"
                              effect="dark"
                          >
                            <span
                                class="masked-info"
                                @click="showFullContactInfo(contact, 'githubUrl')">
                              {{ contact.githubUrl }}
                              <el-icon class="info-lock-icon"><Lock/></el-icon>
                            </span>
                          </el-tooltip>
                          <span v-else>{{ contact.githubUrl }}</span>
                        </span>
                      </div>

                      <div class="info-row" v-if="contact.skills">
                        <span class="info-label-wide">{{ t('linkedin.skills') }}:</span>
                        <span class="info-value">{{ contact.skills }}</span>
                      </div>

                      <div class="info-row" v-if="contact.jobSummary">
                        <span class="info-label-wide">{{ t('linkedin.job.summary') }}:</span>
                        <span class="info-value">{{ contact.jobSummary }}</span>
                      </div>

                      ·                      <!-- 渲染其他可能的非空字段，但排除特定字段 -->
                      <div v-for="(value, key) in getFilteredExtraFields(contact)" :key="key" class="info-row">
                        <span class="info-label-wide">{{ formatFieldName(key) }}:</span>
                        <span class="info-value">{{ value }}</span>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="card-actions">
                  <div class="action-buttons">
                    <el-button
                        type="text"
                        class="detail-btn"
                        @click="toggleContactDetails(contact)"
                    >
                      {{ contact.expanded ? t('linkedin.collapse') : t('linkedin.details') }}
                    </el-button>
                  </div>
                </div>
              </div>

              <!-- 无数据时显示 -->
              <div v-if="paginatedContacts.length === 0 && !loading" class="no-data">
                <i class="el-icon-warning"></i>
                <p>{{ t('linkedin.no.data') }}</p>
              </div>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="Math.min(queryParams.pageNum, Math.max(1, totalPages))"
                  :page-sizes="[10, 20, 50]"
                  :page-size="queryParams.pageSize"
                  layout="sizes, prev, pager, next, jumper"
                  :total="total"
                  background
              >
              </el-pagination>
            </div>
          </div>
        </div>

        <!-- 联系人详情弹窗 -->
        <el-dialog
            :visible.sync="detailsVisible"
            :title="t('linkedin.contact.details')"
            width="70%"
            destroy-on-close
            class="contact-detail-dialog"
            @close="detailsVisible = false"
        >
          <div v-if="currentContact.id" class="contact-resume">
            <!-- 头部:姓名、职位和基本信息 -->
            <div class="resume-header">
              <div class="resume-avatar">
                <el-avatar
                    :size="80"
                    :src="currentContact.avatar || getRandomAvatar(currentContact.id, currentContact.fullName)"
                    @error="handleAvatarError"
                />
              </div>
              <div class="resume-basic">
                <h1 class="resume-name">{{ currentContact.fullName }}</h1>
                <div class="resume-title">
                  {{
                    currentContact.jobTitle ? getJobTitleLabel(currentContact.jobTitle) : t('linkedin.unknown.position')
                  }}
                </div>
                <div class="resume-company">{{ currentContact.companyName || t('linkedin.unknown.company') }}</div>
              </div>
              <div class="resume-location">
                <div class="location-item"><i class="el-icon-location"></i>
                  {{
                    currentContact.location ? getLocationLabel(currentContact.location) : t('linkedin.unknown.location')
                  }}
                </div>
                <div v-if="currentContact.industry" class="industry-item"><i class="el-icon-office-building"></i>
                  {{ getIndustryLabel(currentContact.industry) }}
                </div>
                <div v-if="currentContact.locationCountry && currentContact.locationCountry !== currentContact.location"
                     class="location-item">
                  <i class="el-icon-map-location"></i> {{ formatCountryName(currentContact.locationCountry) }}
                </div>
              </div>
            </div>

            <el-divider/>

            <!-- 联系信息部分 -->
            <div class="resume-contact-info">
              <div class="section-title">{{ t('linkedin.contact.methods') }}</div>
              <div class="contact-grid">
                <div class="contact-item" v-if="currentContact.emails">
                  <i class="el-icon-message"></i>
                  <div class="item-label">{{ t('linkedin.email') }}</div>
                  <div class="item-value">
                    <el-tooltip
                        v-if="currentContact.emails && currentContact.emails.includes('*')"
                        :content="t('linkedin.view.full.contact.tooltip')"
                        placement="top"
                        effect="dark"
                    >
                      <span
                          class="masked-info"
                          @click="showFullContactInfo(currentContact, 'emails')">
                        {{ currentContact.emails }}
                        <el-icon class="info-lock-icon"><Lock/></el-icon>
                      </span>
                    </el-tooltip>
                    <span v-else>{{ currentContact.emails }}</span>
                  </div>
                </div>
                <div class="contact-item" v-if="currentContact.mobile">
                  <i class="el-icon-phone"></i>
                  <div class="item-label">{{ t('linkedin.phone') }}</div>
                  <div class="item-value">
                    <el-tooltip
                        v-if="currentContact.mobile && currentContact.mobile.includes('*')"
                        :content="t('linkedin.view.full.contact.tooltip')"
                        placement="top"
                        effect="dark"
                    >
                      <span
                          class="masked-info"
                          @click="showFullContactInfo(currentContact, 'mobile')">
                        {{ formatPhoneNumber(currentContact.mobile) }}
                        <el-icon class="info-lock-icon"><Lock/></el-icon>
                      </span>
                    </el-tooltip>
                    <span v-else>{{ formatPhoneNumber(currentContact.mobile) }}</span>
                  </div>
                </div>
                <div class="contact-item" v-if="currentContact.linkedinUrl">
                  <i class="el-icon-link"></i>
                  <div class="item-label">{{ t('linkedin.linkedin') }}</div>
                  <div class="item-value">
                    <el-tooltip
                        v-if="currentContact.linkedinUrl && currentContact.linkedinUrl.includes('*')"
                        :content="t('linkedin.view.full.contact.tooltip')"
                        placement="top"
                        effect="dark"
                    >
                      <span
                          class="masked-info"
                          @click="showFullContactInfo(currentContact, 'linkedinUrl')">
                        {{ currentContact.linkedinUrl }}
                        <el-icon class="info-lock-icon"><Lock/></el-icon>
                      </span>
                    </el-tooltip>
                    <a v-else :href="'https://' + currentContact.linkedinUrl" target="_blank">{{
                        currentContact.linkedinUrl
                      }}</a>
                  </div>
                </div>
                <div class="contact-item" v-if="currentContact.facebookUrl">
                  <i class="el-icon-link"></i>
                  <div class="item-label">{{ t('linkedin.facebook') }}</div>
                  <div class="item-value">
                    <el-tooltip
                        v-if="currentContact.facebookUrl && currentContact.facebookUrl.includes('*')"
                        :content="t('linkedin.view.full.contact.tooltip')"
                        placement="top"
                        effect="dark"
                    >
                      <span
                          class="masked-info"
                          @click="showFullContactInfo(currentContact, 'facebookUrl')">
                        {{ currentContact.facebookUrl }}
                        <el-icon class="info-lock-icon"><Lock/></el-icon>
                      </span>
                    </el-tooltip>
                    <a v-else :href="'https://' + currentContact.facebookUrl" target="_blank">{{
                        currentContact.facebookUrl
                      }}</a>
                  </div>
                </div>
                <div class="contact-item" v-if="currentContact.twitterUrl">
                  <i class="el-icon-link"></i>
                  <div class="item-label">{{ t('linkedin.twitter') }}</div>
                  <div class="item-value">
                    <el-tooltip
                        v-if="currentContact.twitterUrl && currentContact.twitterUrl.includes('*')"
                        :content="t('linkedin.view.full.contact.tooltip')"
                        placement="top"
                        effect="dark"
                    >
                      <span
                          class="masked-info"
                          @click="showFullContactInfo(currentContact, 'twitterUrl')">
                        {{ currentContact.twitterUrl }}
                        <el-icon class="info-lock-icon"><Lock/></el-icon>
                      </span>
                    </el-tooltip>
                    <a v-else :href="'https://' + currentContact.twitterUrl" target="_blank">{{
                        currentContact.twitterUrl
                      }}</a>
                  </div>
                </div>
                <div class="contact-item" v-if="currentContact.githubUrl">
                  <i class="el-icon-link"></i>
                  <div class="item-label">{{ t('linkedin.github') }}</div>
                  <div class="item-value">
                    <el-tooltip
                        v-if="currentContact.githubUrl && currentContact.githubUrl.includes('*')"
                        :content="t('linkedin.view.full.contact.tooltip')"
                        placement="top"
                        effect="dark"
                    >
                      <span
                          class="masked-info"
                          @click="showFullContactInfo(currentContact, 'githubUrl')">
                        {{ currentContact.githubUrl }}
                        <el-icon class="info-lock-icon"><Lock/></el-icon>
                      </span>
                    </el-tooltip>
                    <a v-else :href="'https://' + currentContact.githubUrl" target="_blank">{{
                        currentContact.githubUrl
                      }}</a>
                  </div>
                </div>
              </div>
            </div>

            <!-- 工作信息部分 -->
            <div class="resume-work-info">
              <div class="section-title">{{ t('linkedin.work.info') }}</div>
              <div class="work-details">
                <div class="work-item">
                  <div class="company-info" v-if="currentContact.companyName">
                    <div class="company-name">{{ currentContact.companyName }}</div>
                    <div class="company-meta">
                  <span v-if="currentContact.companyIndustry" class="company-industry">{{
                      currentContact.companyIndustry
                    }}</span>
                      <span v-if="currentContact.companySize"
                            class="company-size"> {{ getCompanySizeLabel(currentContact.companySize) }}</span>
                    </div>
                    <div v-if="currentContact.companyWebsite" class="company-website">
                      <el-tooltip
                          v-if="currentContact.companyWebsite && currentContact.companyWebsite.includes('*')"
                          :content="t('linkedin.view.full.contact.tooltip')"
                          placement="top"
                          effect="dark"
                      >
                        <span
                            class="masked-info"
                            @click="showFullContactInfo(currentContact, 'companyWebsite')">
                          {{ currentContact.companyWebsite }}
                          <el-icon class="info-lock-icon"><Lock/></el-icon>
                        </span>
                      </el-tooltip>
                      <a v-else :href="'https://' + currentContact.companyWebsite" target="_blank">{{
                          currentContact.companyWebsite
                        }}</a>
                    </div>
                  </div>

                  <div class="position-info" v-if="currentContact.jobTitle">
                    <div class="position-title">{{ getJobTitleLabel(currentContact.jobTitle) }}</div>
                    <div v-if="currentContact.yearsExperience" class="experience-years"> {{
                        currentContact.yearsExperience
                      }}年工作经验
                    </div>
                    <div v-if="currentContact.inferredSalary" class="salary-info"> 薪资范围
                      {{ currentContact.inferredSalary }}
                    </div>
                  </div>

                  <div class="job-summary" v-if="currentContact.jobSummary">
                    <div class="summary-title">{{ t('linkedin.job.summary') }}</div>
                    <div class="summary-content">{{ currentContact.jobSummary }}</div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 技能部分 -->
            <div class="resume-skills" v-if="currentContact.skills">
              <div class="section-title">技能专长</div>
              <div class="skills-content">
                <el-tag
                    v-for="skill in currentContact.skills.split(',')"
                    :key="skill"
                    size="medium"
                    effect="light"
                    class="skill-tag"
                >
                  {{ skill.trim() }}
                </el-tag>
              </div>
            </div>

            <!-- 添加额外信息部分，显示所有未在其他部分展示的非空字段 -->
            <div class="resume-extra-info" v-if="hasFilteredExtraFields">
              <div class="section-title">其他信息</div>
              <div class="extra-details">
                <div class="extra-item" v-for="(value, key) in filteredExtraFields" :key="key">
                  <div class="extra-label">{{ formatFieldName(key) }}:</div>
                  <div class="extra-value">{{ value }}</div>
                </div>
              </div>
            </div>

            <div class="resume-actions">
              <el-button @click="detailsVisible = false">
                关闭
              </el-button>
            </div>
          </div>
        </el-dialog>

        <!-- 添加到线索弹窗 -->
        <el-dialog
            :visible.sync="addToLeadsVisible"
            title="添加到线索"
            width="500px"
            destroy-on-close
            @close="addToLeadsVisible = false"
        >
          <el-form :model="leadForm" label-width="100px">
            <el-form-item label="备注">
              <el-input v-model="leadForm.remark" type="textarea" :rows="4" placeholder="请输入备注信息"/>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="addToLeadsVisible = false">取消</el-button>
              <el-button type="primary" @click="submitAddToLeads">确认</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>

  <!-- 导出对话框 -->
  <el-dialog
      v-model="exportDialogVisible"
      :title="t('export.dialog.title')"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <div class="export-dialog-content">
      <div class="export-info">
        <p>{{ t('export.matching.records') }}: <span class="export-highlight">{{ displayMatchCount }}</span></p>
        <p>{{ t('export.current.balance') }}: <span class="export-highlight">{{
            userBalance.exportQuotaRemaining
          }}</span></p>
        <p class="export-note">{{ t('export.note') }}</p>
        <p class="export-limit-notice">{{ t('export.max.limit.notice') }}</p>
      </div>

      <!-- 字段选择区域 -->
      <div class="field-selection">
        <div class="field-selection-header">
          <h4>{{ t('export.selectFields') }}</h4>
          <div class="field-selection-actions">
            <el-button
                size="small"
                @click="selectAllFields"
                :disabled="isAllFieldsSelected"
            >
              {{ t('export.selectAll') }}
            </el-button>
            <el-button
                size="small"
                @click="selectNoFields"
                :disabled="isNoFieldsSelected"
            >
              {{ t('export.selectNone') }}
            </el-button>
          </div>
        </div>

        <div class="field-selection-content">
          <div class="field-grid">
            <div
                v-for="field in allFields"
                :key="field.key"
                class="field-item"
            >
              <el-checkbox
                  v-model="field.selected"
                  @change="updateSelectedFields"
              >
                <span :class="{ 'field-unselected': !field.selected }">
                  {{ t(field.labelKey) }}
                </span>
              </el-checkbox>
            </div>
          </div>

          <div v-if="isNoFieldsSelected" class="field-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.noFieldsSelected') }}
          </div>
        </div>
      </div>

      <div class="export-input">
        <p>{{ t('export.enter.count') }}</p>
        <el-input-number
            v-model="exportCount"
            :min="1"
            :max="Math.max(1, Math.min(totalMatchCount, 50000, userBalance.exportQuotaRemaining || 1))"
            :step="100"
            size="large"
            controls-position="right"
        />

        <div class="export-warnings">
          <p v-if="isExportCountExceeded" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.warning.exceed') }}
          </p>
          <p v-if="isBalanceInsufficient" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.warning.balance') }}
          </p>
          <p v-if="isExportLimitExceeded" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.warning.limit') }}
          </p>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exportDialogVisible = false">{{ t('export.cancel') }}</el-button>
        <el-button
            type="primary"
            @click="doExport"
            :loading="exportLoading"
            :disabled="isExportCountExceeded || isBalanceInsufficient || isExportLimitExceeded || !exportCount || isNoFieldsSelected"
        >
          {{ t('export.confirm') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {computed, defineComponent, nextTick, onMounted, reactive, ref, watch} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Lock, Search} from '@element-plus/icons-vue'
import {
  addToMyLeads,
  batchAddToMyLeads,
  exportLinkedinContacts,
  getLinkedinContacts,
  getLinkedinContactsCount,
  getLinkedinFullContactInfo,
  getUserBalanceInfo,
  searchCompanyNamesFromES,   // 新增：查询ES公司名称
  searchJobTitlesFromES,      // 新增：查询ES职位
  searchIndustriesFromES,     // 新增：查询ES行业
  searchLocationsFromES       // 新增：查询ES国家/地区
} from '@/api/linkedin'
import request from '@/utils/request'
import Translate from '@/components/Translate.vue'
import MainHeader from '@/components/MainHeader.vue'
import SideMenu from '@/components/SideMenu.vue'
import {
  addTranslation,
  changeLanguage,
  currentLanguage as globalCurrentLanguage,
  getCurrentLanguage,
  t
} from '@/utils/i18n' // 导入国际化函数
import {debounce} from 'lodash'

export default defineComponent({
  name: 'LinkedInContacts',
  components: {
    Translate,
    MainHeader,
    SideMenu,
    Lock
  },
  data() {
    return {
      // companyFounded: '' // 临时注释掉公司成立时间筛选功能
    }
  },
  setup() {
    // 外部定义ref搜索变量
    const jobTitleSearch = ref('');
    const industrySearch = ref('');
    const locationSearch = ref('');
    const companyNameSearch = ref('');

    // 存储ES查询结果
    const esCompanyNames = ref([]);
    const esJobTitles = ref([]);
    const esIndustries = ref([]);
    const esLocations = ref([]);
    const esSearchLoading = ref({
      companyName: false,
      jobTitle: false,
      industry: false,
      location: false
    });

    // 存储从ES选中的自定义项
    const selectedCustomCompanyNames = ref([]);
    const selectedCustomJobTitles = ref([]);
    const selectedCustomIndustries = ref([]);
    const selectedCustomLocations = ref([]);

    // 临时注释掉公司成立时间筛选相关变量
    // const selectedFoundedYears = ref([]);
    // const foundedYearOptions = ref([]);

    // 导出相关变量
    const exportDialogVisible = ref(false);
    const exportCount = ref(1);
    const exportLoading = ref(false);
    const totalMatchCount = ref(0);
    const userBalance = ref({
      exportQuotaRemaining: 0
    });

    // 符合条件的数量显示相关变量
    const displayedCount = ref(0);
    const countLoading = ref(false);

    // 字段选择相关变量
    const selectedFields = ref([]);
    // 使用全局响应式语言变量，确保语言切换时实时更新
    const currentLanguage = globalCurrentLanguage;

    // 创建国际化字段配置
    const createFieldsConfig = () => {
      return [
        {key: 'fullName', labelKey: 'linkedin.field.fullName', selected: true},
        {key: 'jobTitle', labelKey: 'linkedin.field.headline', selected: true},
        {key: 'companyName', labelKey: 'linkedin.field.currentCompany', selected: true},
        {key: 'emails', labelKey: 'linkedin.field.emails', selected: true},
        {key: 'mobile', labelKey: 'linkedin.field.phoneNumbers', selected: true},
        {key: 'phoneNumbers', labelKey: 'linkedin.field.phoneNumbers', selected: true},
        {key: 'linkedinUrl', labelKey: 'linkedin.field.profileUrl', selected: true},
        {key: 'companyWebsite', labelKey: 'linkedin.field.companyWebsite', selected: true},
        {key: 'industry', labelKey: 'linkedin.field.industry', selected: true},
        {key: 'location', labelKey: 'linkedin.field.location', selected: true},
        {key: 'locationCountry', labelKey: 'linkedin.field.country', selected: true},
        {key: 'companySize', labelKey: 'globalEnterprise.field.companyScale', selected: true},
        // { key: 'companyFounded', labelKey: 'globalEnterprise.field.establishedYear', selected: true }, // 临时注释掉公司成立时间筛选功能
        {key: 'twitterUserName', labelKey: 'linkedin.field.twitterUserName', selected: true},
        {key: 'twitterUrl', labelKey: 'linkedin.field.twitterUrl', selected: true},
        {key: 'githubUrl', labelKey: 'linkedin.field.githubUrl', selected: true},
        {key: 'facebookUrl', labelKey: 'linkedin.field.facebookUrl', selected: true}
      ];
    };

    const allFields = ref(createFieldsConfig());

    const state = reactive({
      loading: false,
      contactsList: [],
      allContacts: [], // 存储所有联系人数据（未应用分页）
      total: 0,
      searchTimeout: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fullName: '',
        companyName: '',
        jobTitle: '',
        industry: '',
        country: ''
      },
      selectedIds: [],
      detailsVisible: false,
      currentContact: {},
      addToLeadsVisible: false,
      leadForm: {
        remark: '',
        contactIds: []
      },
      expanded: {
        jobTitle: false,
        companyName: false,
        location: false,
        contactMethod: false,
        companySize: false,
        // companyFounded: false, // 临时注释掉公司成立时间筛选功能
        industry: false,
      },
      filters: {
        jobTitle: [],
        companyName: [],
        location: [],
        country: [],
        contactMethod: [],
        companySize: [],
        // companyFounded: [], // 临时注释掉公司成立时间筛选功能
        industry: [],
      },
      // 全选状态
      checkAll: {
        jobTitle: false,
        industry: false,
        location: false,
        country: false,
        contactMethod: false,
        companySize: false,
        // companyFounded: false, // 临时注释掉公司成立时间筛选功能
      },
      // 半选状态
      isIndeterminate: {
        jobTitle: false,
        companyName: false,
        location: false,
        country: false,
        contactMethod: false,
        companySize: false,
        // companyFounded: false, // 临时注释掉公司成立时间筛选功能
        industry: false,
      },
      filterOptions: {
        jobTitles: [],
        companyNames: [],
        locations: [],
        countries: [],
        salaryRanges: ['45,000-55,000', '70,000-85,000', '85,000-100,000'],
        companySizes: [],
        industries: []
      },
      // 临时注释掉公司成立时间筛选相关状态
      // companyFoundedMode: 'preset', // 筛选模式：exact, range, preset
      // exactYearInput: '', // 准确年份输入
      // exactYears: [], // 已选择的准确年份列表
      // rangeStartYear: '', // 范围起始年份
      rangeEndYear: '', // 范围结束年份
      // 职位选项 - 扩展更多选项，不仅限于表中数据
      jobTitleOptions: [
        'ndt engineer',
        'medical laboratory technician',
        'laboratory assistant',
        'bookkeeper and office coordinator',
        'software engineer',
        'data analyst',
        'project manager',
        'marketing specialist',
        'sales representative',
        'human resources manager',
        'accountant',
        'financial analyst',
        'operations manager',
        'customer service representative',
        'product manager',
        'graphic designer',
        'content writer',
        'research scientist',
        'network administrator',
        'business analyst',
        'senior software engineer',
        'junior developer',
        'full stack developer',
        'frontend developer',
        'backend developer',
        'devops engineer',
        'quality assurance engineer',
        'data scientist',
        'machine learning engineer',
        'systems administrator',
        'cloud architect',
        'database administrator',
        'IT support specialist',
        'security analyst',
        'UX designer',
        'UI designer',
        'product owner',
        'scrum master',
        'agile coach',
        'sales manager',
        'account executive',
        'marketing manager',
        'digital marketing specialist',
        'content marketing manager',
        'SEO specialist',
        'social media manager',
        'PR specialist',
        'brand manager',
        'customer success manager',
        'technical support engineer',
        'technical writer',
        'chief executive officer',
        'chief financial officer',
        'chief technology officer',
        'chief operating officer',
        'vice president of engineering',
        'vice president of sales',
        'vice president of marketing',
        'director of product',
        'director of engineering',
        'director of marketing'
      ],
      // 行业选项 - 扩展更多选项
      industryOptions: [
        'aviation & aerospace',
        'pharmaceuticals',
        'education management',
        'hospital & health care',
        // 'information technology',
        'financial services',
        // 'manufacturing',
        'retail',
        'telecommunications',
        // 'healthcare',
        'real estate',
        'insurance',
        'automotive',
        // 'media & entertainment',
        'energy',
        // 'professional services',
        'construction',
        // 'transportation',
        // 'agriculture',
        // 'government',
        'biotechnology',
        'chemicals',
        'computer software',
        'computer hardware',
        'computer networking',
        'consumer electronics',
        'consumer goods',
        'defense & space',
        'e-learning',
        // 'e-commerce',
        // 'electrical & electronic manufacturing',
        'environmental services',
        'facilities services',
        'food & beverages',
        'food production',
        'furniture',
        'gambling & casinos',
        'glass, ceramics & concrete',
        'government administration',
        'government relations',
        'graphic design',
        'higher education',
        'hospitality',
        'human resources',
        // 'import & export',
        'industrial automation',
        'internet',
        'investment banking',
        'investment management',
        'legal services',
        'leisure, travel & tourism',
        // 'logistics & supply chain',
        'luxury goods & jewelry',
        'machinery',
        'management consulting',
        'maritime',
        // 'marketing & advertising',
        'market research',
        'mechanical or industrial engineering',
        'medical devices',
        'medical practice',
        'mental health care',
        'military',
        'mining & metals',
        // 'motion pictures & film',
        // 'museums & institutions',
        'music',
        'nanotechnology',
        'non-profit organization management',
        'oil & energy',
        'online media',
        'outsourcing/offshoring',
        'package/freight delivery',
        // 'packaging & containers',
        'paper & forest products',
        'performing arts',
        'plastics',
        'primary/secondary education',
        'printing',
        'public policy',
        // 'public relations & communications',
        'public safety',
        'publishing',
        'railroad manufacture',
        'ranching',
        'research',
        'restaurants',
        'retail',
        // 'security & investigations',
        'semiconductors',
        'shipbuilding',
        'sporting goods',
        'sports',
        // 'staffing & recruiting',
        'supermarkets',
        'textiles',
        'think tanks',
        'tobacco',
        // 'translation & localization',
        'utilities',
        'venture capital & private equity',
        'veterinary',
        'warehousing',
        'wholesale',
        // 'wine & spirits',
        'wireless',
        // 'writing & editing'
      ],
      // 地点选项 - 扩展更多选项
      locationOptions: [
        'United States',
        'China',
        'india',
        'United Kingdom',
        'Canada',
        'Germany',
        'France',
        'Japan',
        // 'Australia',
        // 'Brazil',
        'singapore',
        'spain',
        'italy',
        'netherlands',
        'sweden',
        // 'Russia',
        'mexico',
        'south korea',
        'ireland',
        // 'Switzerland',
        'argentina',
        // 'Austria',
        'belgium',
        'chile',
        'colombia',
        // 'Czech Republic',
        'denmark',
        'egypt',
        'finland',
        'greece',
        // 'Hong Kong',
        'hungary',
        'indonesia',
        'israel',
        'malaysia',
        'new zealand',
        'norway',
        'pakistan',
        'peru',
        'philippines',
        'poland',
        // 'Portugal',
        // 'Qatar',
        // 'Romania',
        'saudi arabia',
        'south africa',
        // 'Taiwan',
        'thailand',
        'turkey',
        // 'Ukraine',
        'united arab emirates',
        'vietnam',
        'bangladesh',
        'bulgaria',
        'croatia',
        // 'Cyprus',
        'estonia',
        'iceland',
        'latvia',
        'lithuania',
        'luxembourg',
        'malta',
        'morocco',
        'nigeria',
        'serbia',
        'slovakia',
        'slovenia',
        // 'Kenya',
        'ghana',
        'jordan',
        'lebanon',
        'algeria',
        'bahrain',
        // 'Kuwait',
        'oman'
      ],
      // 公司规模选项 - 扩展更多选项
      companySizeOptions: [
        'self-employed',
        '1-10',
        '11-50',
        '51-200',
        '201-500',
        '501-1000',
        '1001-5000',
        '5001-10000',
        '10001+'
      ],
      // 薪资范围选项 - 扩展更多选项
      salaryOptions: [
        'under 15,000',
        '15,000-25,000',
        '25,000-35,000',
        '35,000-45,000',
        '45,000-55,000',
        '55,000-65,000',
        '65,000-75,000',
        '75,000-85,000',
        '85,000-95,000',
        '95,000-105,000',
        '105,000-125,000',
        '125,000-150,000',
        '150,000-175,000',
        '175,000-200,000',
        '200,000-250,000',
        '250,000-300,000',
        '300,000-400,000',
        '400,000-500,000',
        '500,000+'
      ],
      // 公司名称选项 - 添加扩展更多选项
      companyNameOptions: [
        'Tech Innovations',
        'Global Healthcare',
        'Shanghai Tech',
        'huddleston technical services',
        'lifesouth community blood centers',
        'jefferson county board of education',
        'Microsoft',
        'Apple',
        'Google',
        'Amazon',
        'Facebook',
        'Alibaba',
        'Tencent',
        'Baidu',
        'IBM',
        'Intel',
        'Oracle',
        'SAP',
        'Xiaomi',
        'TSMC',
        'Sony',
        'Samsung',
        'Huawei',
        'Siemens',
        'General Electric',
        'Johnson and Johnson',
        'Pfizer',
        'Novartis',
        'Roche',
        'Boeing',
        'Airbus'
      ]
    })

    const jumpPage = ref('');

    // 转换API数据到前端使用的格式
    const transformApiData = (data) => {

      if (!Array.isArray(data)) {
        return [];
      }

      const result = data.map((item, index) => {
        return {
          id: item.id,
          mid: item.mid,
          mt: item.mt,
          fullName: item.fullName,
          jobTitle: item.jobTitle,
          subRole: item.subRole,
          industry: item.industry,
          industry2: item.industry2,
          emails: item.emails,
          mobile: item.mobile,  // 更新为与后端匹配的字段
          country: item.country,
          companyName: item.companyName,
          companyIndustry: item.companyIndustry,
          companyWebsite: item.companyWebsite,
          companySize: item.companySize,
          location: item.location,
          locality: item.locality,
          metro: item.metro,
          region: item.region,
          skills: item.skills,
          linkedinUrl: item.linkedinUrl,
          locationCountry: item.locationCountry,
          inferredSalary: item.inferredSalary,
          yearsExperience: item.yearsExperience,
          summary: item.summary,
          interests: item.interests,
          gender: item.gender,
          githubUrl: item.githubUrl,
          twitterUserName: item.twitterUserName,
          twitterUrl: item.twitterUrl,
          facebookUrl: item.facebookUrl,
          // UI交互状态
          expanded: false,
          selected: false
        };
      });

      return result;
    };

    // 数据验证函数
    const validateContactData = (contact) => {
      if (!contact) return false;
      if (!contact.id) return false;
      if (!contact.fullName && !contact.firstName && !contact.lastName) return false;
      return true;
    };


    // 根据筛选条件过滤数据的计算属性
    const filteredContacts = computed(() => {

      if (!state.contactsList.length) {
        return [];
      }

      // 这里可以添加本地筛选逻辑，目前直接返回所有数据
      // 因为筛选主要通过API实现
      return state.contactsList;
    });

    // 分页后的显示数据
    const paginatedContacts = computed(() => {

      if (!state.contactsList.length) {
        return [];
      }

      // 确保总数至少等于当前结果的长度
      if (state.total === 0 && state.contactsList.length > 0) {
        state.total = state.contactsList.length;
      }

      // 限制总数不超过10000
      if (state.total > 10000) {
        state.total = 10000;
      }

      return state.contactsList;
    });

    // 计算总页数，确保结果正确
    const totalPages = computed(() => {
      // 确保总页数正确计算
      const total = state.total || 0;
      // 如果总数特别大，限制最大页数以避免性能问题
      if (total > 10000) {
        return 1000; // 限制最大页数为1000页
      }

      const pageSize = state.queryParams.pageSize || 10;
      const pages = Math.max(1, Math.ceil(total / pageSize));
      return pages;
    });

    // 监听筛选条件变化
    watch(() => state.filters, () => {
      // 更新全选状态
      updateCheckAllStatus();

      // 当筛选条件变化时，重置页码
      state.queryParams.pageNum = 1;
    }, {deep: true});

    // 监听页码大小变化
    watch(() => state.queryParams.pageSize, (newVal, oldVal) => {
      if (newVal !== oldVal) {
        state.queryParams.pageNum = 1; // 切换每页记录数时重置为第一页
        // 当页码大小变化时，需要重新请求数据
        searchByKeyword();
      }
    });

    // 监听总页数变化，确保当前页码不超过总页数
    watch(totalPages, (newTotal) => {
      if (newTotal > 0 && state.queryParams.pageNum > newTotal) {
        state.queryParams.pageNum = newTotal;
        // 页码变化后，确保重新计算分页结果
        nextTick(() => {
        });
      } else if (newTotal === 0 && state.queryParams.pageNum !== 1) {
        state.queryParams.pageNum = 1;
      }
    });

    // 监听总数变化
    watch(() => state.total, (newTotal, oldTotal) => {
      if (newTotal > 0 && oldTotal === 0) {
        // 当总数从0变为有效值时，可能需要重新渲染分页组件
        nextTick(() => {
          // 强制更新视图
          if (state.queryParams.pageNum === 1) {
            // 如果当前页是第一页，临时设为第二页再设回来，触发更新
            state.queryParams.pageNum = 2;
            setTimeout(() => {
              state.queryParams.pageNum = 1;
            }, 0);
          } else {
            // 如果不是第一页，设为第一页触发更新
            state.queryParams.pageNum = 1;
          }
        });
      }
    });

    // 监听exportCount，确保导出数量不超过符合条件的记录数
    watch(exportCount, (newExportCount) => {
      if (newExportCount > totalMatchCount.value) {
        exportCount.value = totalMatchCount.value;
      }
    });

    // 处理全选变化
    const handleCheckAllChange = (type) => {
      let options = [];

      // 根据不同类型获取对应的选项列表
      switch (type) {
        case 'jobTitle':
          options = filteredJobTitles.value;
          break;
        case 'companyName':
          options = filteredCompanyNames.value;
          break;
        case 'industry':
          options = filteredIndustries.value;
          break;
        case 'location':
          options = filteredLocations.value;
          break;
        case 'contactMethod':
          options = ['email', 'phone', 'linkedin', 'companyWebsite', 'facebookUrl', 'twitterUrl', 'githubUrl'];
          break;
        case 'companySize':
          options = state.companySizeOptions;
          break;
          // case 'companyFounded': // 临时注释掉公司成立时间筛选功能
          //   options = ['after_2020', '2015_2020', '2010_2015', '2005_2010', '2000_2005', 'before_2000'];
          //   break;
        default:
          options = [];
      }

      // 根据全选状态设置筛选条件
      if (state.checkAll[type]) {
        state.filters[type] = [...options];
        state.isIndeterminate[type] = false;
      } else {
        // 设置为空数组，表示不应用该筛选条件
        state.filters[type] = [];
        state.isIndeterminate[type] = false;
      }

      // 使用防抖处理，避免频繁发送请求
      if (filterDebounceTimer.value) {
        clearTimeout(filterDebounceTimer.value);
      }

      filterDebounceTimer.value = setTimeout(() => {
        // 更新后立即触发搜索
        searchByKeyword();
      }, 300);
    };

    // 更新全选状态
    const updateCheckAllStatus = () => {
      // 更新职位全选状态
      if (filteredJobTitles.value.length > 0) {
        state.checkAll.jobTitle = filteredJobTitles.value.length === state.filters.jobTitle.length;
        state.isIndeterminate.jobTitle = state.filters.jobTitle.length > 0 && state.filters.jobTitle.length < filteredJobTitles.value.length;
      }

      // 更新公司名称全选状态
      if (filteredCompanyNames.value.length > 0) {
        state.checkAll.companyName = filteredCompanyNames.value.length === state.filters.companyName.length;
        state.isIndeterminate.companyName = state.filters.companyName.length > 0 && state.filters.companyName.length < filteredCompanyNames.value.length;
      }

      // 更新行业全选状态
      if (filteredIndustries.value.length > 0) {
        state.checkAll.industry = filteredIndustries.value.length === state.filters.industry.length;
        state.isIndeterminate.industry = state.filters.industry.length > 0 && state.filters.industry.length < filteredIndustries.value.length;
      }

      // 更新地点全选状态
      if (filteredLocations.value.length > 0) {
        state.checkAll.location = filteredLocations.value.length === state.filters.location.length;
        state.isIndeterminate.location = state.filters.location.length > 0 && state.filters.location.length < filteredLocations.value.length;
      }

      // 更新联系方式全选状态（包含URL选项）
      const contactMethodOptions = ['email', 'phone', 'linkedin', 'companyWebsite', 'facebookUrl', 'twitterUrl', 'githubUrl'];
      state.checkAll.contactMethod = contactMethodOptions.length === state.filters.contactMethod.length;
      state.isIndeterminate.contactMethod = state.filters.contactMethod.length > 0 && state.filters.contactMethod.length < contactMethodOptions.length;

      // 更新公司规模全选状态
      if (state.companySizeOptions.length > 0) {
        state.checkAll.companySize = state.companySizeOptions.length === state.filters.companySize.length;
        state.isIndeterminate.companySize = state.filters.companySize.length > 0 && state.filters.companySize.length < state.companySizeOptions.length;
      }

      // 临时注释掉公司成立时间全选状态更新
      // const companyFoundedOptions = ['after_2020', '2015_2020', '2010_2015', '2005_2010', '2000_2005', 'before_2000'];
      // state.checkAll.companyFounded = companyFoundedOptions.length === state.filters.companyFounded.length;
      // state.isIndeterminate.companyFounded = state.filters.companyFounded.length > 0 && state.filters.companyFounded.length < companyFoundedOptions.length;
    };

    // 获取列表数据
    const getList = async () => {
      try {
        state.loading = true;
        // 创建请求参数对象，包含有效的筛选条件
        const requestParams = {
          ...state.queryParams,
          // 添加所选的筛选条件，只发送用户勾选的选项
          companyName: state.filters.companyName && state.filters.companyName.length > 0 ?
              state.filters.companyName.join(',') : '',
          jobTitle: state.filters.jobTitle && state.filters.jobTitle.length > 0 ?
              state.filters.jobTitle.join(',') : '',
          industry: state.filters.industry && state.filters.industry.length > 0 ?
              state.filters.industry.join(',') : '',
          country: state.filters.location && state.filters.location.length > 0 ?
              state.filters.location.join(',') : '',
          // 添加联系方式筛选（包含URL筛选）
          contactMethod: state.filters.contactMethod && state.filters.contactMethod.length > 0 ?
              state.filters.contactMethod.join(',') : '',
          // 添加公司规模筛选
          companySize: state.filters.companySize && state.filters.companySize.length > 0 ?
              state.filters.companySize.join(',') : '',
          // 临时注释掉公司成立时间筛选
          // companyFounded: state.filters.companyFounded && state.filters.companyFounded.length > 0 ?
          //     state.filters.companyFounded.join(',') : ''
        };

        const response = await getLinkedinContacts(requestParams);
        if (response && response.code === 200) {

          // 处理后端返回的数据格式
          const responseData = response.data && response.data.data ? response.data.data : response.data;

          let totalCount = responseData.total || responseData.count || (responseData.list && responseData.list.length) || 0;
          // 限制总数不超过10000
          if (totalCount > 10000) {
            totalCount = 10000;
          }
          state.total = totalCount;

          state.contactsList = transformApiData(responseData.list || []);

          // 从数据中提取筛选器选项
          updateFilterOptions(state.contactsList);
        } else {
          const msg = (response && response.msg) || '';
          if (msg.includes('余额不足')) {
            if (state.queryParams.pageNum !== 1) {
              state.queryParams.pageNum = 1;
            }
            return;
          }
        }
      } catch (error) {

        // 余额不足时仅重置到第一页并返回
        try {
          const errMsg = (error && (error.response?.data?.message || error.message)) || '';
          if (errMsg.includes('余额不足')) {
            if (state.queryParams.pageNum !== 1) {
              state.queryParams.pageNum = 1;
            }
            return;
          }
        } catch (_) { /* ignore */
        }

        // 检查是否为网络错误
        if (error.message && error.message.includes('Network Error')) {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error('网络连接失败，请检查后端服务是否启动');
          } else {
            ElMessage.error('Network connection failed, please check if the backend service is started');
          }
        } else if (error.response && error.response.status === 500) {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error('服务器内部错误(500)，请联系管理员');
          } else {
            ElMessage.error('Server internal error(500), please contact the administrator');
          }
        } else {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error('获取联系人列表失败: ' + (error.message || '未知错误'));
          } else {
            ElMessage.error('Failed to get contact list: ' + (error.message || 'Unknown error'));
          }
        }
      } finally {
        state.loading = false;
      }
    };

    // 使用search接口进行搜索
    const searchByKeyword = async () => {
      try {
        state.loading = true;
        const keyword = state.queryParams.fullName || '';

        // 构建包含中英文的筛选参数
        const filterParams = buildI18nFilterParams();

        // 调用search接口
        // 注意：这里page参数使用pageNum-1是因为后端分页从0开始，而前端从1开始
        const apiResponse = await request({
          url: `/linkedin/search?keyword=${encodeURIComponent(keyword)}&page=${state.queryParams.pageNum - 1}&size=${state.queryParams.pageSize}${filterParams}`,
          method: 'get'
        });

        if (apiResponse && apiResponse.code === 200) {

          // 更健壮的数据解析逻辑
          let responseData;
          let dataList;

          if (apiResponse.data) {
            responseData = apiResponse.data;
          } else {
            responseData = apiResponse;
          }

          // 获取列表数据
          if (responseData.list && Array.isArray(responseData.list)) {
            dataList = responseData.list;
          } else if (Array.isArray(responseData)) {
            dataList = responseData;
          } else {
            dataList = [];
          }

          // 获取总数 - 这是分页的关键
          let newTotal = responseData.total || responseData.count || (dataList && dataList.length) || 0;

          // 限制总数不超过10000
          if (newTotal > 10000) {
            newTotal = 10000;
          }

          // 设置总数并确保视图更新
          state.total = newTotal;

          // 确保当前页码不超过总页数
          const maxPage = Math.ceil(state.total / state.queryParams.pageSize);
          if (state.queryParams.pageNum > maxPage) {
            state.queryParams.pageNum = Math.max(1, maxPage);
          }

          state.contactsList = transformApiData(dataList);

          // 从数据中提取筛选器选项
          updateFilterOptions(state.contactsList);

        } else {
          const msg = (apiResponse && apiResponse.msg) || '';
          if (msg.includes('余额不足')) {
            if (state.queryParams.pageNum !== 1) {
              state.queryParams.pageNum = 1;
            }
            return;
          }
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error('获取联系人数据失败');
          } else {
            ElMessage.error('Failed to get contact data');
          }
        }
      } catch (error) {
        // 余额不足时仅重置到第一页并返回
        try {
          const errMsg = (error && (error.response?.data?.message || error.message)) || '';
          if (errMsg.includes('余额不足')) {
            if (state.queryParams.pageNum !== 1) {
              state.queryParams.pageNum = 1;
            }
            return;
          }
        } catch (_) { /* ignore */
        }
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error('搜索失败: ' + (error.message || '未知错误'));
        } else {
          ElMessage.error('Search failed, please try again later.')
        }
      } finally {
        state.loading = false;
      }
    };

    // 从联系人数据中更新筛选器选项
    const updateFilterOptions = (contactsList, isInitialLoad = false) => {
      if (!Array.isArray(contactsList) || contactsList.length === 0) {
        return;
      }

      // 创建一个字段映射，用于计数
      const fieldCounts = {
        jobTitles: new Map(),
        companyNames: new Map(),
        industries: new Map(),
        locations: new Map(),
        companySizes: new Map()
      };

      // 统计各个字段的值出现次数
      contactsList.forEach(contact => {
        // 职位统计
        if (contact.jobTitle) {
          const count = fieldCounts.jobTitles.get(contact.jobTitle) || 0;
          fieldCounts.jobTitles.set(contact.jobTitle, count + 1);
        }

        // 公司名称统计
        if (contact.companyName) {
          const count = fieldCounts.companyNames.get(contact.companyName) || 0;
          fieldCounts.companyNames.set(contact.companyName, count + 1);
        }

        // 行业统计
        if (contact.industry) {
          const count = fieldCounts.industries.get(contact.industry) || 0;
          fieldCounts.industries.set(contact.industry, count + 1);
        }

        // 地点统计
        if (contact.locationCountry) {
          const count = fieldCounts.locations.get(contact.locationCountry) || 0;
          fieldCounts.locations.set(contact.locationCountry, count + 1);
        }

        // 公司规模统计
        if (contact.companySize) {
          const count = fieldCounts.companySizes.get(contact.companySize) || 0;
          fieldCounts.companySizes.set(contact.companySize, count + 1);
        }
      });

      // 将字段值添加到筛选器选项
      state.filterOptions.jobTitles = [...fieldCounts.jobTitles.keys()];
      state.filterOptions.companyNames = [...fieldCounts.companyNames.keys()];
      state.filterOptions.industries = [...fieldCounts.industries.keys()];
      state.filterOptions.locations = [...fieldCounts.locations.keys()];
      state.filterOptions.companySizes = [...fieldCounts.companySizes.keys()];

    };

    // 获取随机头像 - 改进版本，支持多种 ID 类型和一致的 seed 生成
    const getRandomAvatar = (id, name) => {
      // 生成一致的数值 hash，用于选择头像风格和 seed
      const generateConsistentHash = (input) => {
        if (!input) return 0;

        let hash = 0;
        const str = String(input).toLowerCase();
        for (let i = 0; i < str.length; i++) {
          const char = str.charCodeAt(i);
          hash = ((hash << 5) - hash) + char;
          hash = hash & hash; // Convert to 32bit integer
        }
        return Math.abs(hash);
      };

      // 优先使用姓名生成 seed，确保同一个人的头像保持一致
      let seed = '';
      let hashValue = 0;

      if (name && name.trim()) {
        // 使用姓名生成 seed
        seed = name.toLowerCase().replace(/\s+/g, '');
        hashValue = generateConsistentHash(name);
      } else if (id) {
        // 如果没有姓名，使用 ID 生成 seed
        seed = String(id).toLowerCase();
        hashValue = generateConsistentHash(id);
      } else {
        // 如果都没有，使用默认值
        seed = 'default';
        hashValue = 0;
      }

      // 为不同用户使用不同的风格，增加多样性
      const styles = ['micah', 'avataaars', 'adventurer', 'bottts', 'personas'];
      const styleIndex = hashValue % styles.length;
      const style = styles[styleIndex];

      // 生成头像 URL，添加参数确保一致性
      return `https://api.dicebear.com/7.x/${style}/svg?seed=${seed}&scale=80`;
    };

    // 处理头像加载错误 - 改进版本，使用一致的 seed
    const handleAvatarError = (e) => {
      // 加载失败时使用备用头像
      // 从当前 src 中提取 seed，确保使用相同的 seed
      const currentSrc = e.target.src || '';
      const seedMatch = currentSrc.match(/seed=([^&]+)/);
      const seed = seedMatch ? seedMatch[1] : 'fallback';

      // 使用不同的风格作为备用
      const fallbackStyles = ['avataaars', 'bottts', 'personas', 'adventurer'];
      const styleIndex = Math.abs(seed.charCodeAt(0)) % fallbackStyles.length;
      const fallbackStyle = fallbackStyles[styleIndex];

      // 设置备用头像 URL
      e.target.src = `https://api.dicebear.com/7.x/${fallbackStyle}/svg?seed=${seed}&scale=80`;
    };

    // 生成首字母头像 - 基于联系人姓名的首字母
    const getInitialAvatar = (name) => {
      if (!name || !name.trim()) {
        return 'https://api.dicebear.com/7.x/initials/svg?seed=U&backgroundColor=random';
      }

      // 提取首字母
      const names = name.trim().split(/\s+/);
      let initials = '';

      if (names.length >= 2) {
        // 如果有多个单词，取第一个和最后一个单词的首字母
        initials = (names[0][0] + names[names.length - 1][0]).toUpperCase();
      } else if (names.length === 1) {
        // 如果只有一个单词，取前两个字母
        initials = names[0].substring(0, 2).toUpperCase();
      }

      // 使用 initials 风格生成头像
      return `https://api.dicebear.com/7.x/initials/svg?seed=${initials}&backgroundColor=random&fontColor=fff`;
    };

    // 获取国家旗帜图标
    const getCountryFlag = (country) => {
      if (!country) return 'https://flagcdn.com/w20/un.png';

      // 国家代码映射
      const countryCodeMap = {
        'united states': 'us',
        'china': 'cn',
        'india': 'in',
        'united kingdom': 'gb',
        'canada': 'ca',
        'germany': 'de',
        'france': 'fr',
        'japan': 'jp',
        'australia': 'au',
        'brazil': 'br',
        'singapore': 'sg',
        'spain': 'es',
        'italy': 'it',
        'netherlands': 'nl',
        'sweden': 'se',
        'russia': 'ru',
        'mexico': 'mx',
        'south korea': 'kr',
        'ireland': 'ie',
        'switzerland': 'ch',
        'philippines': 'ph',
        'uk': 'gb'
      };

      const countryCode = countryCodeMap[country.toLowerCase()];
      return countryCode ? `https://flagcdn.com/w20/${countryCode}.png` : 'https://flagcdn.com/w20/un.png';
    };

    // 处理单个选择框变化
    const handleSingleSelection = (contact, selected) => {
      if (selected) {
        state.selectedIds.push(contact.id);
      } else {
        const index = state.selectedIds.indexOf(contact.id);
        if (index > -1) {
          state.selectedIds.splice(index, 1);
        }
      }
    };

    // 临时注释掉初始化年份选项函数
    // const initFoundedYearOptions = () => {
    //   const currentYear = new Date().getFullYear();
    //   const years = [];
    //   // 生成从1900年到当前年份的选项
    //   for (let year = currentYear; year >= 1900; year--) {
    //     years.push(year.toString());
    //   }
    //   foundedYearOptions.value = years;
    // };

    // 获取符合条件的联系人数量
    const fetchContactsCount = async () => {
      try {
        countLoading.value = true;

        const params = {
          fullName: state.queryParams.fullName || ''
        };

        // 添加筛选条件: 公司名称
        if (state.filters.companyName && state.filters.companyName.length > 0) {
          params.companyName = state.filters.companyName.join(',');
        }

        // 添加筛选条件: 职位
        if (state.filters.jobTitle && state.filters.jobTitle.length > 0) {
          params.jobTitle = state.filters.jobTitle.join(',');
        }

        // 添加筛选条件: 行业
        if (state.filters.industry && state.filters.industry.length > 0) {
          params.industry = state.filters.industry.join(',');
        }

        // 添加筛选条件: 国家/地区
        if (state.filters.location && state.filters.location.length > 0) {
          params.country = state.filters.location.join(',');
        }

        // 添加筛选条件: 联系方式（包含URL筛选）
        if (state.filters.contactMethod && state.filters.contactMethod.length > 0) {
          params.contactMethod = state.filters.contactMethod.join(',');
        }

        // 添加筛选条件: 公司规模
        if (state.filters.companySize && state.filters.companySize.length > 0) {
          params.companySize = state.filters.companySize.join(',');
        }

        // 临时注释掉公司成立时间筛选条件
        // if (state.filters.companyFounded && state.filters.companyFounded.length > 0) {
        //   params.companyFounded = state.filters.companyFounded.join(',');
        // }

        const response = await getLinkedinContactsCount(params);

        if (response.code === 200) {
          const count = response.data.count || 0;
          // 限制显示数量为10000
          displayedCount.value = count > 10000 ? '10,000+' : formatNumber(count);
          return count;
        } else {
          displayedCount.value = 0;
          return 0;
        }
      } catch (error) {
        displayedCount.value = 0;
        return 0;
      } finally {
        countLoading.value = false;
      }
    };

    // 数字格式化函数
    const formatNumber = (num) => {
      if (num === null || num === undefined) return '0';
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    };

    // 字段选择相关函数
    const initSelectedFields = () => {
      selectedFields.value = allFields.value.filter(field => field.selected).map(field => field.key);
    };

    const toggleField = (fieldKey) => {
      const field = allFields.value.find(f => f.key === fieldKey);
      if (field) {
        field.selected = !field.selected;
        updateSelectedFields();
      }
    };

    const updateSelectedFields = () => {
      const newSelectedFields = allFields.value.filter(field => field.selected).map(field => field.key);
      selectedFields.value = newSelectedFields;
    };

    const selectAllFields = () => {
      allFields.value.forEach(field => {
        field.selected = true;
      });
      updateSelectedFields();
    };

    const selectNoFields = () => {
      allFields.value.forEach(field => {
        field.selected = false;
      });
      updateSelectedFields();
    };

    const isAllFieldsSelected = computed(() => {
      const result = allFields.value.length > 0 && allFields.value.every(field => field.selected);
      return result;
    });

    const isNoFieldsSelected = computed(() => {
      const result = allFields.value.length > 0 && allFields.value.every(field => !field.selected);
      return result;
    });

    // 处理敏感信息的点击事件 - 获取完整联系信息
    const showFullContactInfo = async (contact, field) => {
      // 只有当信息包含星号时才需要查询完整信息
      if (!(contact[field] && contact[field].includes('*'))) {
        return;
      }

      try {
        // 弹出确认对话框
        await ElMessageBox.confirm(
            t('linkedin.confirm.view.contact'),
            t('linkedin.view.full.contact'),
            {
              confirmButtonText: t('linkedin.confirm'),
              cancelButtonText: t('linkedin.cancel'),
              type: 'warning'
            }
        );

        const response = await getLinkedinFullContactInfo(contact.mid, contact.mt, field);

        if (response.code === 200 && response.data) {
          // 更新当前联系人的信息
          if (response.data[field]) {

            // 方法1: 直接更新字段值（应该能触发响应式更新）
            contact[field] = response.data[field];

            // 方法2: 同时更新contactsList中对应的联系人数据，确保所有引用都更新
            // 注意：现在使用mysqlId和mysqlTable组合来查找联系人
            const contactIndex = state.contactsList.findIndex(c =>
                c.mysqlId === contact.mysqlId && c.mysqlTable === contact.mysqlTable);
            if (contactIndex !== -1) {
              state.contactsList[contactIndex][field] = response.data[field];
            }

            // 方法3: 如果当前联系人详情弹窗打开，也要更新currentContact
            if (state.currentContact &&
                state.currentContact.mid === contact.mid &&
                state.currentContact.mt === contact.mt) {
              state.currentContact[field] = response.data[field];
            }
          }

          ElMessage.success(t('linkedin.contact.view.success'));
        } else {
          ElMessage.error(response.msg || t('linkedin.contact.view.error'));
        }
      } catch (error) {
        if (error !== 'cancel') {
          // 处理特定错误，如余额不足
          if (error.response && error.response.data && error.response.data.msg) {
            ElMessage.error(error.response.data.msg);
          } else {
            ElMessage.error(t('linkedin.contact.view.error'));
          }
        }
      }
    };

    onMounted(() => {
      // 添加一个自定义翻译
      addTranslation('linkedin.no.pagination', {
        zh: '暂无分页信息',
        en: 'No pagination information'
      });
      // 添加敏感信息处理相关的翻译键
      addTranslation('linkedin.view.full.contact.tooltip', {
        zh: '点击消耗一次次数查看完整信息',
        en: 'Click to view full information (costs 1 credit)'
      });

      // 添加字段翻译
      addTranslation('linkedin.field.githubUrl', {
        zh: 'GitHub链接',
        en: 'GitHub URL'
      });

      addTranslation('linkedin.field.facebookUrl', {
        zh: 'Facebook链接',
        en: 'Facebook URL'
      });

      // 添加导出弹窗相关翻译
      addTranslation('export.dialog.title', {
        zh: '导出数据',
        en: 'Export Data'
      });

      addTranslation('export.matching.records', {
        zh: '符合条件的记录数',
        en: 'Matching records'
      });

      addTranslation('export.current.balance', {
        zh: '当前导出余额',
        en: 'Current export balance'
      });

      addTranslation('export.note', {
        zh: '注意: 每导出一条记录将消耗一点导出额度',
        en: 'Note: Each exported record will consume one export credit'
      });

      addTranslation('export.enter.count', {
        zh: '请输入要导出的记录数:',
        en: 'Please enter the number of records to export:'
      });

      addTranslation('export.warning.exceed', {
        zh: '导出数量不能超过符合条件的记录数',
        en: 'Export quantity cannot exceed the number of matching records'
      });

      addTranslation('export.warning.balance', {
        zh: '导出余额不足',
        en: 'Insufficient export balance'
      });

      addTranslation('export.warning.limit', {
        zh: '导出数量不能超过50000条',
        en: 'Export quantity cannot exceed 50,000 records'
      });

      addTranslation('export.cancel', {
        zh: '取消',
        en: 'Cancel'
      });

      addTranslation('export.confirm', {
        zh: '确认导出',
        en: 'Confirm Export'
      });

      addTranslation('linkedin.confirm.view.contact', {
        zh: '查看完整联系信息将消耗一次查看次数，是否继续？',
        en: 'Viewing full contact information will cost 1 credit. Continue?'
      });

      addTranslation('linkedin.view.full.contact', {
        zh: '查看完整联系信息',
        en: 'View Full Contact Information'
      });

      addTranslation('linkedin.confirm', {
        zh: '确认',
        en: 'Confirm'
      });

      addTranslation('linkedin.cancel', {
        zh: '取消',
        en: 'Cancel'
      });

      addTranslation('linkedin.contact.view.success', {
        zh: '联系信息获取成功',
        en: 'Contact information retrieved successfully'
      });

      addTranslation('linkedin.contact.view.error', {
        zh: '获取联系信息失败，请稍后重试',
        en: 'Failed to retrieve contact information, please try again later'
      });

      // 添加导出相关提示的翻译
      addTranslation('export.loading.preparing', {
        en: 'Preparing export data, please wait...',
        zh: '正在准备导出数据，请稍候...'
      });
      addTranslation('export.progress.processing', {
        en: 'Processing large data export, this may take several minutes...',
        zh: '正在处理大量数据导出，可能需要几分钟时间...'
      });
      addTranslation('export.large.data.title', {
        en: 'Large Data Export Warning',
        zh: '大数据量导出警告'
      });
      addTranslation('export.large.data.warning', {
        en: 'You are about to export a very large amount of data (over 30,000 records). This operation may take up to 10 minutes to complete and puts significant load on the server. Please confirm that you really need this many records.',
        zh: '您即将导出超大量数据（超过30,000条记录）。这个操作可能需要长达10分钟才能完成，并且会给服务器带来较大负载。请确认您确实需要这么多数据。'
      });
      addTranslation('export.large.data.confirm', {
        en: 'Continue with Export',
        zh: '继续导出'
      });
      addTranslation('export.success.completed', {
        en: 'Export completed successfully!',
        zh: '导出成功完成！'
      });

      // 添加ES搜索相关翻译
      addTranslation('linkedin.filter.es.results', {
        zh: '搜索结果',
        en: 'Search Results'
      });

      addTranslation('linkedin.filter.loading', {
        zh: '搜索中...',
        en: 'Searching...'
      });
      addTranslation('export.error.limitExceeded', {
        en: 'Export count cannot exceed 50,000 records',
        zh: '导出数量不能超过50,000条记录'
      });

      addTranslation('export.max.limit.notice', {
        en: 'Maximum export limit is 50,000 records',
        zh: '最多可导出50000条记录'
      });

      // 检查登录状态
      const token = localStorage.getItem('token');
      if (!token) {
        ElMessage.error('请先登录');
        // 添加一个小延迟，让错误消息显示出来
        setTimeout(() => {
          window.location.href = '/#/login';
        }, 1000);
        return;
      }

      // 临时注释掉初始化年份选项
      // initFoundedYearOptions();

      // 初始化选中的字段
      initSelectedFields();

      // 设置一个标志，表示正在初始化，避免重复请求
      const initializing = true;

      // 先初始化所有筛选条件为空
      initAllFilters();

      // 然后在初始化完成后调用一次搜索
      nextTick(() => {
        // 首次加载时只调用一次API请求
        searchByKeyword();
        // 同时获取符合条件的数量
        fetchContactsCount();
      });
    });

    // 初始化所有筛选条件为空
    const initAllFilters = () => {
      // 初始化筛选条件，但不触发搜索
      Object.keys(state.filters).forEach(key => {
        if (Array.isArray(state.filters[key])) {
          state.filters[key] = [];
        }
      });

      // 设置全选状态为false，表示未选择任何选项
      Object.keys(state.checkAll).forEach(key => {
        state.checkAll[key] = false;
      });

      // 设置不确定状态
      Object.keys(state.isIndeterminate).forEach(key => {
        state.isIndeterminate[key] = false;
      });
    };

    // 处理查询
    const handleSearch = () => {
      state.queryParams.pageNum = 1;
      getList();
    };

    // 处理姓名搜索
    const handleNameSearch = () => {
      state.queryParams.pageNum = 1;
      // 使用search接口而不是list接口
      searchByKeyword();
    };

    // 处理姓名输入变化，添加防抖功能
    const handleNameInputChange = () => {
      if (state.searchTimeout) {
        clearTimeout(state.searchTimeout);
      }

      state.searchTimeout = setTimeout(() => {
        state.queryParams.pageNum = 1;
        searchByKeyword();
        // 同时更新符合条件的数量
        fetchContactsCount();
      }, 300);
    };

    // 重置姓名搜索
    const resetNameSearch = () => {
      // 如果已经是空值，则不重新加载数据，避免循环调用
      if (state.queryParams.fullName === '') {
        return;
      }

      state.queryParams.fullName = '';
      state.queryParams.pageNum = 1;
      // 使用search接口而不是list接口
      searchByKeyword();
    };

    // 表格选择事件
    const handleSelectionChange = (selection) => {
      state.selectedIds = selection.map(item => item.id);
    };

    // 显示联系人详情
    const showDetails = (row) => {
      state.currentContact = row;
      state.detailsVisible = true;
    };

    // 切换联系人卡片详情展开/收起状态
    const toggleContactDetails = (contact) => {
      contact.expanded = !contact.expanded;
    };

    // 添加单个联系人到线索
    const handleAddToLeads = (row) => {
      if (row) {
        state.leadForm.contactIds = [row.id];
      } else if (state.selectedIds.length === 0) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.warning('请先选择联系人');
        } else {
          ElMessage.warning('Please select a contact');
        }
        return;
      } else {
        state.leadForm.contactIds = [...state.selectedIds];
      }
      state.addToLeadsVisible = true;
    };

    // 提交添加到线索
    const submitAddToLeads = async () => {
      try {
        if (state.leadForm.contactIds.length === 1) {
          // 单个添加
          await addToMyLeads(state.leadForm.contactIds[0], {remark: state.leadForm.remark});
        } else {
          // 批量添加
          await batchAddToMyLeads({
            ids: state.leadForm.contactIds,
            remark: state.leadForm.remark
          });
        }
        if (getCurrentLanguage() === 'zh') {
          ElMessage.success('添加成功');
        } else {
          ElMessage.success('Added successfully');
        }
        state.addToLeadsVisible = false;
        state.leadForm.remark = '';
        state.leadForm.contactIds = [];
      } catch (error) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error('添加失败');
        } else {
          ElMessage.error('Failed to add');
        }
      }
    };

    // 处理导出
    const handleExport = async () => {
      try {
        exportLoading.value = true;
        if (getCurrentLanguage() === 'zh') {
          ElMessage.info('正在准备导出数据，请稍候...');
        } else {
          ElMessage.info('Preparing export data, please wait...');
        }

        // 先获取符合条件的记录数量
        await fetchExportCount();

        // 再获取用户余额
        await fetchUserBalance();

        // 显示导出对话框
        exportDialogVisible.value = true;
      } catch (error) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error('准备导出失败，请稍后重试');
        } else {
          ElMessage.error('Failed to prepare export data, please try again later');
        }
      } finally {
        exportLoading.value = false;
      }
    };

    // 获取符合条件的记录数量
    const fetchExportCount = async () => {
      try {
        const params = {
          fullName: state.queryParams.fullName || ''
        };

        // 添加筛选条件: 公司名称
        if (state.filters.companyName && state.filters.companyName.length > 0) {
          params.companyName = state.filters.companyName.join(',');
        }

        // 添加筛选条件: 职位
        if (state.filters.jobTitle && state.filters.jobTitle.length > 0) {
          params.jobTitle = state.filters.jobTitle.join(',');
        }

        // 添加筛选条件: 行业
        if (state.filters.industry && state.filters.industry.length > 0) {
          params.industry = state.filters.industry.join(',');
        }

        // 添加筛选条件: 国家/地区
        if (state.filters.location && state.filters.location.length > 0) {
          params.country = state.filters.location.join(',');
        }

        // 添加筛选条件: 联系方式（包含URL筛选）
        if (state.filters.contactMethod && state.filters.contactMethod.length > 0) {
          params.contactMethod = state.filters.contactMethod.join(',');
        }

        // 添加筛选条件: 公司规模
        if (state.filters.companySize && state.filters.companySize.length > 0) {
          params.companySize = state.filters.companySize.join(',');
        }

        // 临时注释掉公司成立时间筛选条件
        // if (state.filters.companyFounded && state.filters.companyFounded.length > 0) {
        //   params.companyFounded = state.filters.companyFounded.join(',');
        // }

        const response = await getLinkedinContactsCount(params);

        if (response.code === 200) {
          const count = response.data.count || 0;

          // 保存实际总数到state.total中，用于显示"50000+"
          state.total = count;

          // 限制导出数量为50000
          totalMatchCount.value = count > 50000 ? 50000 : count;
          // 更新导出数量，不超过符合条件的记录数，默认为1000或符合条件总数
          exportCount.value = Math.min(totalMatchCount.value, 1000);
          return count;
        } else {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error(response.msg || '获取记录数量失败');
          } else {
            ElMessage.error('Failed to get record count');
          }
          return 0;
        }
      } catch (error) {
        if (getCurrentLanguage() === 'zh'){
          ElMessage.error('获取记录数量失败，请稍后重试');
        } else {
          ElMessage.error('Failed to get record count');
        }
        return 0;
      }
    };

    // 获取用户余额
    const fetchUserBalance = async () => {
      try {
        const response = await getUserBalanceInfo();
        if (response.code === 200 && response.data) {
          userBalance.value = response.data;
          return response.data;
        } else {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error(response.msg || '获取余额信息失败');
          } else {
            ElMessage.error('Failed to get balance information');
          }
          return {exportQuotaRemaining: 0};
        }
      } catch (error) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error('获取余额信息失败，请稍后重试');
        } else {
          ElMessage.error('Failed to get balance information');
        }
        return {exportQuotaRemaining: 0};
      }
    };

    // 执行导出操作
    const doExport = async () => {
      // 检查字段选择
      if (isNoFieldsSelected.value) {
        ElMessage.error(t('export.error.noFieldsSelected'));
        return;
      }

      // 检查导出数量
      if (isExportCountExceeded.value) {
        ElMessage.error(t('export.error.countExceeded', {maxCount: totalMatchCount.value}));
        return;
      }

      // 检查导出上限
      if (isExportLimitExceeded.value) {
        ElMessage.error(t('export.error.limitExceeded'));
        return;
      }

      // 检查余额
      if (isBalanceInsufficient.value) {
        ElMessage.error(t('export.error.balanceInsufficient'));
        return;
      }

      // 确保导出数量是有效的数字
      if (!exportCount.value || isNaN(Number(exportCount.value)) || Number(exportCount.value) <= 0) {
        ElMessage.error(t('export.error.invalidCount'));
        return;
      }

      exportLoading.value = true;
      try {
        // 准备导出参数对象
        const exportParams = {
          exportCount: Number(exportCount.value), // 添加导出数量参数
          selectedFields: selectedFields.value.join(','), // 添加选中的字段列表
          language: currentLanguage.value // 添加当前语言参数
        };

        // 添加搜索关键词
        if (state.queryParams.fullName) {
          exportParams.fullName = state.queryParams.fullName;
        }

        // 添加筛选条件: 公司名称
        if (state.filters.companyName && state.filters.companyName.length > 0) {
          exportParams.companyName = state.filters.companyName.join(',');
        }

        // 添加筛选条件: 职位
        if (state.filters.jobTitle && state.filters.jobTitle.length > 0) {
          exportParams.jobTitle = state.filters.jobTitle.join(',');
        }

        // 添加筛选条件: 行业
        if (state.filters.industry && state.filters.industry.length > 0) {
          exportParams.industry = state.filters.industry.join(',');
        }

        // 添加筛选条件: 国家/地区
        if (state.filters.location && state.filters.location.length > 0) {
          exportParams.country = state.filters.location.join(',');
        }

        // 独立处理国家字段，如果前端存在独立国家筛选条件
        if (state.filters.country && state.filters.country.length > 0) {
          exportParams.country = state.filters.country.join(',');
        }

        // 添加筛选条件: 联系方式（包含URL筛选）
        if (state.filters.contactMethod && state.filters.contactMethod.length > 0) {
          exportParams.contactMethod = state.filters.contactMethod.join(',');
        }

        // 添加筛选条件: 公司规模
        if (state.filters.companySize && state.filters.companySize.length > 0) {
          exportParams.companySize = state.filters.companySize.join(',');
        }

        // 临时注释掉公司成立时间筛选条件
        // if (state.filters.companyFounded && state.filters.companyFounded.length > 0) {
        //   exportParams.companyFounded = state.filters.companyFounded.join(',');
        // }

        ElMessage.info(t('export.loading.preparing'));

        // 对于大数据量导出，显示提示信息
        if (exportCount.value > 10000) {
          ElMessage.warning(t('export.progress.processing'));
        }

        // 发送请求
        const response = await exportLinkedinContacts(exportParams);
        if (!response || !response.data) {
          if (getCurrentLanguage() === 'zh') {
            throw new Error('导出失败');
          } else {
            throw new Error('Export failed');
          }
        }

        if (!(response.data instanceof Blob)) {
          if (getCurrentLanguage() === 'zh') {
            throw new Error('导出失败：格式不正确');
          } else {
            throw new Error('Export failed: Invalid format');
          }
        }

        // 获取Content-Type
        const contentType = response.headers && response.headers['content-type']
            ? response.headers['content-type']
            : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

        // 检查是否是错误响应
        if (contentType.includes('json')) {
          // 可能是错误响应，尝试解析
          const reader = new FileReader();

          // 使用Promise包装FileReader
          const readJsonResponse = new Promise((resolve, reject) => {
            reader.onload = function () {
              try {
                const result = reader.result;
                const errorResponse = JSON.parse(result);
                resolve(errorResponse);
              } catch (e) {
                if (getCurrentLanguage() === 'zh') {
                  reject(new Error('导出失败'));
                } else {
                  reject(new Error('Export failed'));
                }
              }
            };
            reader.onerror = function (e) {
              if (getCurrentLanguage() === 'zh') {
                reject(new Error('导出失败'));
              } else {
                reject(new Error('Export failed'));
              }
            };
          });

          reader.readAsText(response.data);

          try {
            const errorData = await readJsonResponse;
            // 显示具体的错误信息
            const errorMessage = errorData.msg || errorData.message || '未知错误';
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error(`导出失败`);
            } else {
              ElMessage.error(`Export failed`);
            }

            // 如果错误与参数相关，可能需要提示用户修改导出数量
            if (errorMessage.includes('exportCount') || errorMessage.includes('导出数量')) {
              if (getCurrentLanguage() === 'zh') {
                ElMessage.warning('请检查导出数量是否正确设置');
              } else {
                ElMessage.warning('Please check if the export count is correctly set');
              }
            }

            return;
          } catch (e) {
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error(e.message || '导出失败')
            } else {
              ElMessage.error('Export failed')
            }
            return;
          }
        }

        // 创建Blob对象
        const blob = new Blob([response.data], {type: contentType});

        // 获取文件名（支持国际化）
        const fileNamePrefix = currentLanguage.value === 'en' ? 'LinkedIn_Data' : 'LinkedIn数据';
        let fileName = fileNamePrefix + '.xlsx';
        const disposition = response.headers && response.headers['content-disposition'];
        if (disposition && disposition.includes('filename=')) {
          const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
          const matches = filenameRegex.exec(disposition);
          if (matches != null && matches[1]) {
            fileName = matches[1].replace(/['"]/g, '');
            try {
              fileName = decodeURIComponent(fileName);
            } catch (e) {
            }
          }
        }

        // 下载文件
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);

        // 关闭导出对话框
        exportDialogVisible.value = false;

        // 更新用户余额
        await fetchUserBalance();

        // 记录导出次数
        let key = 'exportCount_linkedin';
        let count = parseInt(localStorage.getItem(key) || '0');
        localStorage.setItem(key, count + 1);

        ElMessage.success(t('export.success.completed'));
      } catch (error) {
        ElMessage.error(t('export.error.failed'));
      } finally {
        exportLoading.value = false;
      }
    };

    // 导出相关的计算属性
    const isExportCountExceeded = computed(() => {
      return exportCount.value > totalMatchCount.value;
    });

    const isBalanceInsufficient = computed(() => {
      return exportCount.value > userBalance.value.exportQuotaRemaining;
    });

    // 显示用的匹配数量（当大于等于50000时显示为"50000+"）
    const displayMatchCount = computed(() => {
      // 使用实际总数，不是受限制的totalMatchCount
      return state.total >= 50000 ? "50000+" : String(totalMatchCount.value);
    });

    const isExportLimitExceeded = computed(() => {
      return exportCount.value > 50000;
    });

    // 上一页
    const handlePrev = () => {
      if (state.queryParams.pageNum > 1) {
        state.queryParams.pageNum -= 1;
        getList();
      }
    };

    // 下一页
    const handleNext = () => {
      state.queryParams.pageNum += 1;
      getList();
    };

    // 跳转到指定页面
    const handleJumpPage = () => {
      const pageNum = parseInt(jumpPage.value);
      if (!isNaN(pageNum) && pageNum > 0) {
        state.queryParams.pageNum = pageNum;
        getList();
      }
      jumpPage.value = '';
    };

    // Element UI分页组件的事件处理方法
    const handleSizeChange = (val) => {
      state.queryParams.pageSize = val;
      state.queryParams.pageNum = 1; // 切换每页记录数时重置为第一页

      // 使用searchByKeyword而不是getList，因为这是LinkedIn页面的主要搜索方法
      searchByKeyword();
    };

    const handleCurrentChange = (val) => {
      // 确保页码在有效范围内
      if (totalPages.value > 0) {
        state.queryParams.pageNum = Math.min(Math.max(1, val), totalPages.value);
      } else {
        state.queryParams.pageNum = 1;
      }

      // 始终请求新数据，因为后端分页需要请求对应页的数据
      searchByKeyword();
    };

    // 切换筛选器展开状态
    const toggleFilter = (filter) => {
      state.expanded[filter] = !state.expanded[filter];
    };

    // 格式化名字（首字母大写）
    const formatName = (name) => {
      if (!name) {
        return '';
      }

      try {
        return name.split(' ')
            .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
            .join(' ');
      } catch (error) {
        return String(name);
      }
    };

    // 处理国旗加载错误
    const handleFlagError = (e) => {
      // 设置默认国旗 (UN flag)
      e.target.src = 'https://flagcdn.com/w20/un.png';
    };

    // 国家名称格式化（保留原始英文名称）
    const formatCountryName = (countryName) => {
      if (!countryName) return '';

      // 返回原始国家名称，首字母大写
      return countryName.split(' ')
          .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
          .join(' ');
    };

    // 通用搜索匹配函数 - 支持中英文搜索
    const matchesSearch = (item, searchTerm, translationFn) => {
      if (!searchTerm) return true;

      // 检查英文原值是否匹配
      if (item.toLowerCase().includes(searchTerm.toLowerCase())) return true;

      // 获取并检查翻译值是否匹配
      const translatedValue = translationFn(item);
      return translatedValue.toLowerCase().includes(searchTerm.toLowerCase());
    };

    // 根据搜索过滤职位列表 - 支持中英文搜索，同时保证选中的项始终可见
    const filteredJobTitles = computed(() => {
      // 获取已选中的自定义项
      const customSelected = state.filters.jobTitle?.filter(item =>
          !state.jobTitleOptions.includes(item)) || [];

      // 更新自定义选中项状态
      selectedCustomJobTitles.value = customSelected;

      if (!jobTitleSearch.value) return state.jobTitleOptions;

      // 先获取已选中的静态项
      const selectedStaticItems = state.filters.jobTitle?.filter(item =>
          state.jobTitleOptions.includes(item)) || [];

      // 搜索匹配的项
      const matchedItems = state.jobTitleOptions.filter(item =>
          matchesSearch(item, jobTitleSearch.value, getJobTitleLabel)
      );

      // 确保已选中的静态项始终显示在列表中
      const alreadyIncluded = new Set(matchedItems);
      selectedStaticItems.forEach(item => {
        if (!alreadyIncluded.has(item)) {
          matchedItems.unshift(item); // 将选中的项添加到列表前面
        }
      });

      return matchedItems;
    });

    // 根据搜索过滤行业列表 - 支持中英文搜索，同时保证选中的项始终可见
    const filteredIndustries = computed(() => {
      // 获取已选中的自定义项
      const customSelected = state.filters.industry?.filter(item =>
          !state.industryOptions.includes(item)) || [];

      // 更新自定义选中项状态
      selectedCustomIndustries.value = customSelected;

      if (!industrySearch.value) return state.industryOptions;

      // 先获取已选中的静态项
      const selectedStaticItems = state.filters.industry?.filter(item =>
          state.industryOptions.includes(item)) || [];

      // 搜索匹配的项
      const matchedItems = state.industryOptions.filter(item =>
          matchesSearch(item, industrySearch.value, getIndustryLabel)
      );

      // 确保已选中的静态项始终显示在列表中
      const alreadyIncluded = new Set(matchedItems);
      selectedStaticItems.forEach(item => {
        if (!alreadyIncluded.has(item)) {
          matchedItems.unshift(item); // 将选中的项添加到列表前面
        }
      });

      return matchedItems;
    });

    // 根据搜索过滤地点列表 - 支持中英文搜索，同时保证选中的项始终可见
    const filteredLocations = computed(() => {
      // 获取已选中的自定义项
      const customSelected = state.filters.location?.filter(item =>
          !state.locationOptions.includes(item)) || [];

      // 更新自定义选中项状态
      selectedCustomLocations.value = customSelected;

      if (!locationSearch.value) return state.locationOptions;

      // 先获取已选中的静态项
      const selectedStaticItems = state.filters.location?.filter(item =>
          state.locationOptions.includes(item)) || [];

      // 搜索匹配的项
      const matchedItems = state.locationOptions.filter(item =>
          matchesSearch(item, locationSearch.value, getLocationLabel)
      );

      // 确保已选中的静态项始终显示在列表中
      const alreadyIncluded = new Set(matchedItems);
      selectedStaticItems.forEach(item => {
        if (!alreadyIncluded.has(item)) {
          matchedItems.unshift(item); // 将选中的项添加到列表前面
        }
      });

      return matchedItems;
    });

    // 根据搜索过滤公司名称列表 - 支持中英文搜索，同时保证选中的项始终可见
    const filteredCompanyNames = computed(() => {
      // 获取已选中的自定义项
      const customSelected = state.filters.companyName?.filter(item =>
          !state.companyNameOptions.includes(item)) || [];

      // 更新自定义选中项状态
      selectedCustomCompanyNames.value = customSelected;

      if (!companyNameSearch.value) return state.companyNameOptions;

      // 先获取已选中的静态项
      const selectedStaticItems = state.filters.companyName?.filter(item =>
          state.companyNameOptions.includes(item)) || [];

      // 搜索匹配的项
      const matchedItems = state.companyNameOptions.filter(item =>
          matchesSearch(item, companyNameSearch.value, getCompanyNameLabel)
      );

      // 确保已选中的静态项始终显示在列表中
      const alreadyIncluded = new Set(matchedItems);
      selectedStaticItems.forEach(item => {
        if (!alreadyIncluded.has(item)) {
          matchedItems.unshift(item); // 将选中的项添加到列表前面
        }
      });

      return matchedItems;
    });

    // 重置所有筛选条件
    const resetAllFilters = (fromUserClick = true) => {
      // 设置所有全选状态为false
      Object.keys(state.checkAll).forEach(key => {
        state.checkAll[key] = false;
      });

      // 清空搜索框
      jobTitleSearch.value = '';
      industrySearch.value = '';
      locationSearch.value = '';
      companyNameSearch.value = '';

      // 清空ES搜索结果
      esCompanyNames.value = [];
      esJobTitles.value = [];
      esIndustries.value = [];
      esLocations.value = [];

      // 清空所有筛选条件
      state.filters.jobTitle = [];
      state.filters.companyName = [];
      state.filters.industry = [];
      state.filters.location = [];
      state.filters.contactMethod = [];
      state.filters.companySize = [];
      // state.filters.companyFounded = []; // 临时注释掉公司成立时间筛选功能

      // 临时注释掉年份选择器重置
      // selectedFoundedYears.value = [];

      // 更新全选状态
      updateCheckAllStatus();

      // 重置页码
      state.queryParams.pageNum = 1;

      // 只有在用户主动点击重置按钮时才显示消息和重新加载数据
      if (fromUserClick) {
        // 提示用户
        if (getCurrentLanguage() === 'zh') {
          ElMessage.success('已重置所有筛选条件');
        } else {
          ElMessage.success('All filters have been reset');
        }
        // 重新加载数据
        searchByKeyword();
        // 同时更新符合条件的数量
        fetchContactsCount();
      }
    };

    // 格式化邮箱，显示部分遮挡的邮箱
    const formatEmail = (email) => {
      if (!email) return '';
      const parts = email.split('@');
      if (parts.length !== 2) return email;

      const name = parts[0];
      const domain = parts[1];

      if (name.length <= 3) {
        return email;
      }

      return `${name.substring(0, 3)}***@${domain}`;
    };

    // 格式化电话号码，根据格式添加分隔符
    const formatPhoneNumber = (phone) => {
      if (!phone) return '';
      // 转为字符串并格式化
      const phoneStr = String(phone);
      if (phoneStr.length >= 11) {
        return `${phoneStr.substring(0, 3)}-${phoneStr.substring(3, 7)}-${phoneStr.substring(7)}`;
      }
      return phoneStr;
    };

    // 计算额外字段
    const hasExtraFields = computed(() => {
      return Object.keys(extraFields.value).length > 0;
    });

    // 获取所有未在其他部分显示的字段
    const extraFields = computed(() => {
      if (!state.currentContact) return {};

      // 已经在页面上展示的字段
      const displayedFields = [
        'id', 'fullName', 'companyName', 'jobTitle', 'industry', 'locationCountry',
        'emails', 'mobile', 'location', 'companyWebsite', 'companySize',
        'linkedinUrl', 'facebookUrl', 'twitterUrl', 'githubUrl', 'skills', 'jobSummary', 'companyIndustry', 'inferredSalary',
        'yearsExperience', 'avatar'
      ];

      // 需要排除的字段（不显示）
      const excludedFields = ['expanded'];

      const extras = {};

      // 遍历当前联系人的所有属性
      for (const key in state.currentContact) {
        // 如果该字段不在已展示列表中，不在排除列表中，且值不为空
        if (!displayedFields.includes(key) &&
            !excludedFields.includes(key) &&
            state.currentContact[key] !== null &&
            state.currentContact[key] !== undefined &&
            state.currentContact[key] !== '') {
          extras[key] = state.currentContact[key];
        }
      }

      return extras;
    });

    // 计算过滤后的额外字段
    const hasFilteredExtraFields = computed(() => {
      return Object.keys(filteredExtraFields.value).length > 0;
    });

    // 获取过滤后的额外字段（排除特定字段）
    const filteredExtraFields = computed(() => {
      if (!state.currentContact) return {};

      // 获取所有额外字段
      const allExtraFields = extraFields.value;

      // 需要排除的特定字段
      const excludeSpecificFields = ['firstName', 'lastName', /* 'companyFounded', */ 'gender', 'industry2', 'mid', 'mt']; // 临时注释掉companyFounded排除

      // 确保这些重要字段不会被排除在显示之外
      const importantFields = ['country', 'facebookUrl', 'twitterUrl', 'githubUrl'];

      // 过滤掉不需要显示的字段
      const filteredExtras = {};
      for (const key in allExtraFields) {
        // 如果是重要字段或者不在排除列表中，则显示
        if (importantFields.includes(key) || !excludeSpecificFields.includes(key)) {
          filteredExtras[key] = allExtraFields[key];
        }
      }

      return filteredExtras;
    });

    // 格式化字段名称，使其更具可读性
    const formatFieldName = (fieldName) => {
      // 特殊处理Expanded字段
      if (fieldName === 'Expanded') {
        return '展开状态';
      }

      // 特殊处理需要国际化的字段
      const specialFields = {
        'country': 'linkedin.field.country',
        'facebookUrl': 'linkedin.field.facebookUrl',
        'twitterUrl': 'linkedin.field.twitterUrl',
        'githubUrl': 'linkedin.field.githubUrl'
      };

      // 如果是特殊字段，使用i18n翻译
      if (specialFields[fieldName]) {
        return t(specialFields[fieldName]);
      }

      // 其他字段的处理
      return fieldName
          .replace(/([A-Z])/g, ' $1') // 在大写字母前添加空格
          .replace(/^./, (str) => str.toUpperCase()) // 首字母大写
          .trim(); // 移除多余空格
    };

    // 获取公司规模的国际化标签（用于显示）
    const getCompanySizeLabel = (size) => {
      return t(`linkedin.company.size.${size}`);
    };

    // 获取公司规模的中文翻译（专门用于API传递）
    const getCompanySizeChineseLabel = (size) => {
      if (!size) return size;
      const key = `linkedin.company.size.${size}`;

      try {
        // 临时切换到中文获取翻译
        const currentLang = getCurrentLanguage();
        changeLanguage('zh');
        const chineseTranslation = t(key);
        changeLanguage(currentLang); // 恢复原语言

        return chineseTranslation === key ? size : chineseTranslation;
      } catch (error) {
        return size;
      }
    };

    // 获取职位的国际化标签（用于显示）
    const getJobTitleLabel = (jobTitle) => {
      if (!jobTitle) return jobTitle;
      const key = `linkedin.job.${jobTitle.toLowerCase().replace(/\s+/g, '_').replace(/[^\w_]/g, '_')}`;
      const translated = t(key);
      // 如果翻译不存在，返回原始值
      return translated === key ? jobTitle : translated;
    };

    // 获取职位的中文翻译（专门用于API传递）
    const getJobTitleChineseLabel = (jobTitle) => {
      if (!jobTitle) return jobTitle;
      const key = `linkedin.job.${jobTitle.toLowerCase().replace(/\s+/g, '_').replace(/[^\w_]/g, '_')}`;

      try {
        // 临时切换到中文获取翻译
        const currentLang = getCurrentLanguage();
        changeLanguage('zh');
        const chineseTranslation = t(key);
        changeLanguage(currentLang); // 恢复原语言

        // 如果翻译不存在，返回原始值
        return chineseTranslation === key ? jobTitle : chineseTranslation;
      } catch (error) {
        return jobTitle;
      }
    };

    // 获取行业的国际化标签（用于显示）
    const getIndustryLabel = (industry) => {
      if (!industry) return industry;
      const key = `linkedin.industry.${industry.toLowerCase()
          .replace(/\s+/g, '_')
          .replace(/&/g, 'and')
          .replace(/[^\w_]/g, '_')
          .replace(/_+/g, '_')
          .replace(/^_|_$/g, '')}`;
      const translated = t(key);
      // 如果翻译不存在，返回原始值
      return translated === key ? industry : translated;
    };

    // 获取行业的中文翻译（专门用于API传递）
    const getIndustryChineseLabel = (industry) => {
      if (!industry) return industry;
      const key = `linkedin.industry.${industry.toLowerCase()
          .replace(/\s+/g, '_')
          .replace(/&/g, 'and')
          .replace(/[^\w_]/g, '_')
          .replace(/_+/g, '_')
          .replace(/^_|_$/g, '')}`;

      try {
        // 临时切换到中文获取翻译
        const currentLang = getCurrentLanguage();
        changeLanguage('zh');
        const chineseTranslation = t(key);
        changeLanguage(currentLang); // 恢复原语言

        return chineseTranslation === key ? industry : chineseTranslation;
      } catch (error) {
        return industry;
      }
    };

    // 获取地点的国际化标签（用于显示）
    const getLocationLabel = (location) => {
      if (!location) return location;
      const key = `linkedin.location.${location.toLowerCase().replace(/\s+/g, '_').replace(/[^\w_]/g, '_')}`;
      const translated = t(key);
      // 如果翻译不存在，返回原始值
      return translated === key ? location : translated;
    };

    // 获取地点的中文翻译（专门用于API传递）
    const getLocationChineseLabel = (location) => {
      if (!location) return location;
      const key = `linkedin.location.${location.toLowerCase().replace(/\s+/g, '_').replace(/[^\w_]/g, '_')}`;

      try {
        // 临时切换到中文获取翻译
        const currentLang = getCurrentLanguage();
        changeLanguage('zh');
        const chineseTranslation = t(key);
        changeLanguage(currentLang); // 恢复原语言

        return chineseTranslation === key ? location : chineseTranslation;
      } catch (error) {
        return location;
      }
    };

    // 获取公司名称的国际化标签（用于显示）
    const getCompanyNameLabel = (companyName) => {
      if (!companyName) return companyName;
      const key = `linkedin.company.${companyName.toLowerCase()
          .replace(/\s+/g, '_')
          .replace(/[^\w_]/g, '_')
          .replace(/_+/g, '_')
          .replace(/^_|_$/g, '')}`;
      const translated = t(key);
      // 如果翻译不存在，返回原始值
      return translated === key ? companyName : translated;
    };

    // 获取公司名称的中文翻译（专门用于API传递）
    const getCompanyNameChineseLabel = (companyName) => {
      if (!companyName) return companyName;
      const key = `linkedin.company.${companyName.toLowerCase()
          .replace(/\s+/g, '_')
          .replace(/[^\w_]/g, '_')
          .replace(/_+/g, '_')
          .replace(/^_|_$/g, '')}`;

      try {
        // 临时切换到中文获取翻译
        const currentLang = getCurrentLanguage();
        changeLanguage('zh');
        const chineseTranslation = t(key);
        changeLanguage(currentLang); // 恢复原语言

        return chineseTranslation === key ? companyName : chineseTranslation;
      } catch (error) {
        return companyName;
      }
    };

    // 获取薪资范围的国际化标签
    const getSalaryLabel = (salary) => {
      if (!salary) return salary;
      const key = `linkedin.salary.${salary}`;
      const translated = t(key);
      // 如果翻译不存在，返回原始值
      return translated === key ? salary : translated;
    };

    // 转换筛选条件为包含中英文的数组格式
    const transformFilterToI18nArray = (filterArray, translationFn) => {
      if (!Array.isArray(filterArray) || filterArray.length === 0) {
        return [];
      }

      const result = [];
      filterArray.forEach(item => {
        result.push(item); // 英文原值
        result.push(translationFn(item)); // 中文翻译
      });

      return result;
    };

    // // 测试国际化函数是否正常工作
    // const testI18nFunctions = () => {
    //   console.log('=== 测试国际化函数 ===');
    //
    //   try {
    //     console.log('当前语言:', getCurrentLanguage());
    //     console.log('t函数测试:', t('common.welcome'));
    //
    //     // 测试中文翻译函数
    //     console.log('职位中文翻译测试:', getJobTitleChineseLabel('software engineer'));
    //     console.log('行业中文翻译测试:', getIndustryChineseLabel('information technology'));
    //     console.log('地点中文翻译测试:', getLocationChineseLabel('united states'));
    //     console.log('公司名称中文翻译测试:', getCompanyNameChineseLabel('Microsoft'));
    //     console.log('公司规模中文翻译测试:', getCompanySizeChineseLabel('1-10'));
    //
    //     console.log('=== 国际化函数测试完成 ===');
    //     return true;
    //   } catch (error) {
    //     console.error('国际化函数测试失败:', error);
    //     return false;
    //   }
    // };

    // 构建包含中英文的筛选参数
    const buildI18nFilterParams = () => {
      let filterParams = '';

      // 添加公司名称筛选 - 包含中英文
      if (state.filters.companyName && state.filters.companyName.length > 0) {
        const i18nCompanyNames = transformFilterToI18nArray(state.filters.companyName, getCompanyNameChineseLabel);
        filterParams += `&companyName=${encodeURIComponent(i18nCompanyNames.join(','))}`;
      }

      // 添加职位筛选 - 包含中英文
      if (state.filters.jobTitle && state.filters.jobTitle.length > 0) {
        const i18nJobTitles = transformFilterToI18nArray(state.filters.jobTitle, getJobTitleChineseLabel);
        filterParams += `&jobTitle=${encodeURIComponent(i18nJobTitles.join(','))}`;
      }

      // 添加行业筛选 - 包含中英文
      if (state.filters.industry && state.filters.industry.length > 0) {
        const i18nIndustries = transformFilterToI18nArray(state.filters.industry, getIndustryChineseLabel);
        filterParams += `&industry=${encodeURIComponent(i18nIndustries.join(','))}`;
      }

      // 添加地点筛选 - 包含中英文
      if (state.filters.location && state.filters.location.length > 0) {
        const i18nLocations = transformFilterToI18nArray(state.filters.location, getLocationChineseLabel);
        filterParams += `&country=${encodeURIComponent(i18nLocations.join(','))}`;
      }

      // 添加公司规模筛选 - 包含中英文
      if (state.filters.companySize && state.filters.companySize.length > 0) {
        const i18nCompanySizes = transformFilterToI18nArray(state.filters.companySize, getCompanySizeChineseLabel);
        filterParams += `&companySize=${encodeURIComponent(i18nCompanySizes.join(','))}`;
      }

      // 联系方式筛选（包含URL筛选）保持原格式（因为它们已经是简单的标识符）
      if (state.filters.contactMethod && state.filters.contactMethod.length > 0) {
        filterParams += `&contactMethod=${encodeURIComponent(state.filters.contactMethod.join(','))}`;
      }

      // 临时注释掉公司成立时间筛选
      // if (state.filters.companyFounded && state.filters.companyFounded.length > 0) {
      //   filterParams += `&companyFounded=${encodeURIComponent(state.filters.companyFounded.join(','))}`;
      // }

      return filterParams;
    };

    // 获取联系人的额外字段（未在卡片上固定显示的字段）
    const getExtraFields = (contact) => {
      if (!contact) return {};

      // 已经在卡片上固定显示的字段
      const displayedFields = [
        'id', 'fullName', 'companyName', 'jobTitle', 'industry', 'locationCountry',
        'emails', 'mobile', 'location', 'companyWebsite', 'companySize',
        'linkedinUrl', 'facebookUrl', 'twitterUrl', 'githubUrl', 'skills', 'jobSummary', 'companyIndustry', 'inferredSalary',
        'yearsExperience', 'avatar', 'selected'
      ];

      // 需要排除的字段（不显示）
      const excludedFields = ['expanded', 'mid', 'mt'];

      const extras = {};

      // 遍历联系人的所有属性
      for (const key in contact) {
        // 如果该字段不在已展示列表中，不在排除列表中，且值不为空
        if (!displayedFields.includes(key) &&
            !excludedFields.includes(key) &&
            contact[key] !== null &&
            contact[key] !== undefined &&
            contact[key] !== '') {
          extras[key] = contact[key];
        }
      }

      return extras;
    };

    // 获取过滤后的额外字段（排除特定字段）
    const getFilteredExtraFields = (contact) => {
      if (!contact) return {};

      // 获取所有额外字段
      const allExtraFields = getExtraFields(contact);

      // 需要排除的特定字段
      const excludeSpecificFields = ['firstName', 'lastName', /* 'companyFounded', */ 'gender', 'industry2', 'mid', 'mt']; // 临时注释掉companyFounded排除

      // 确保这些重要字段不会被排除在显示之外
      const importantFields = ['country', 'facebookUrl', 'twitterUrl', 'githubUrl'];

      // 过滤掉不需要显示的字段
      const filteredExtras = {};
      for (const key in allExtraFields) {
        // 如果是重要字段或者不在排除列表中，则显示
        if (importantFields.includes(key) || !excludeSpecificFields.includes(key)) {
          filteredExtras[key] = allExtraFields[key];
        }
      }

      return filteredExtras;
    };

    // 筛选防抖定时器
    const filterDebounceTimer = ref(null);

    // 临时注释掉处理年份选择器变化函数
    // const handleFoundedYearChange = (selectedYears) => {
    //   // 将选中的年份添加到筛选条件中
    //   const yearFilters = selectedYears.map(year => `year_${year}`);

    //   // 合并年份筛选和预设范围筛选
    //   const existingRangeFilters = state.filters.companyFounded.filter(item =>
    //     !item.startsWith('year_')
    //   );

    //   state.filters.companyFounded = [...existingRangeFilters, ...yearFilters];

    //   // 更新全选状态
    //   updateCheckAllStatus();

    //   // 触发搜索
    //   handleFilterChange('companyFounded');
    // };

    // 处理单个筛选条件变化
    const handleFilterChange = (type) => {
      // 更新indeterminate状态
      updateCheckAllStatus();

      // 使用防抖处理，避免频繁发送请求
      if (filterDebounceTimer.value) {
        clearTimeout(filterDebounceTimer.value);
      }

      filterDebounceTimer.value = setTimeout(() => {
        // 触发API请求
        searchByKeyword();
        // 同时更新符合条件的数量
        fetchContactsCount();
      }, 300); // 300毫秒的防抖延迟
    };

    // 当公司名称选项变化时，更新已选中项状态
    const handleCompanyNameItemChange = () => {
      // 当有项被选中时，从ES结果中移除已选中项，避免重复显示
      if (state.filters.companyName.length > 0 && esCompanyNames.value.length > 0) {
        esCompanyNames.value = esCompanyNames.value.filter(
            company => !state.filters.companyName.includes(company)
        );
      }

      // 更新全选状态
      updateCheckAllStatus();

      // 触发搜索
      handleFilterChange('companyName');
    };

    // 当职位选项变化时，更新已选中项状态
    const handleJobTitleItemChange = () => {
      // 当有项被选中时，从ES结果中移除已选中项，避免重复显示
      if (state.filters.jobTitle.length > 0 && esJobTitles.value.length > 0) {
        esJobTitles.value = esJobTitles.value.filter(
            jobTitle => !state.filters.jobTitle.includes(jobTitle)
        );
      }

      // 更新全选状态
      updateCheckAllStatus();

      // 触发搜索
      handleFilterChange('jobTitle');
    };

    // 当行业选项变化时，更新已选中项状态
    const handleIndustryItemChange = () => {
      // 当有项被选中时，从ES结果中移除已选中项，避免重复显示
      if (state.filters.industry.length > 0 && esIndustries.value.length > 0) {
        esIndustries.value = esIndustries.value.filter(
            industry => !state.filters.industry.includes(industry)
        );
      }

      // 更新全选状态
      updateCheckAllStatus();

      // 触发搜索
      handleFilterChange('industry');
    };

    // 当地点选项变化时，更新已选中项状态
    const handleLocationItemChange = () => {
      // 当有项被选中时，从ES结果中移除已选中项，避免重复显示
      if (state.filters.location.length > 0 && esLocations.value.length > 0) {
        esLocations.value = esLocations.value.filter(
            location => !state.filters.location.includes(location)
        );
      }

      // 更新全选状态
      updateCheckAllStatus();

      // 触发搜索
      handleFilterChange('location');
    };

    // 处理城市搜索
    const handleCompanyNameSearch = debounce(async (val) => {
      if (!val || val.length < 2) {
        esCompanyNames.value = [];
        return;
      }

      try {
        esSearchLoading.value.companyName = true;
        const response = await searchCompanyNamesFromES(val);
        if (response && response.code === 200 && response.data) {
          // 过滤掉已经存在于静态列表中的公司名称
          const staticCompanyList = state.companyNameOptions;
          esCompanyNames.value = response.data.filter(company => !staticCompanyList.includes(company));
        } else {
          esCompanyNames.value = [];
        }
      } catch (error) {
        esCompanyNames.value = [];
      } finally {
        esSearchLoading.value.companyName = false;
      }
    }, 500);

    // 处理职位搜索
    const handleJobTitleSearch = debounce(async (val) => {
      if (!val || val.length < 2) {
        esJobTitles.value = [];
        return;
      }

      try {
        esSearchLoading.value.jobTitle = true;
        const response = await searchJobTitlesFromES(val);
        if (response && response.code === 200 && response.data) {
          // 过滤掉已经存在于静态列表中的职位
          const staticJobTitleList = state.jobTitleOptions;
          esJobTitles.value = response.data.filter(jobTitle => !staticJobTitleList.includes(jobTitle));
        } else {
          esJobTitles.value = [];
        }
      } catch (error) {
        esJobTitles.value = [];
      } finally {
        esSearchLoading.value.jobTitle = false;
      }
    }, 500);

    // 处理行业搜索
    const handleIndustrySearch = debounce(async (val) => {
      if (!val || val.length < 2) {
        esIndustries.value = [];
        return;
      }

      try {
        esSearchLoading.value.industry = true;
        const response = await searchIndustriesFromES(val);
        if (response && response.code === 200 && response.data) {
          // 过滤掉已经存在于静态列表中的行业
          const staticIndustryList = state.industryOptions;
          esIndustries.value = response.data.filter(industry => !staticIndustryList.includes(industry));
        } else {
          esIndustries.value = [];
        }
      } catch (error) {
        esIndustries.value = [];
      } finally {
        esSearchLoading.value.industry = false;
      }
    }, 500);

    // 处理地点搜索
    const handleLocationSearch = debounce(async (val) => {
      if (!val || val.length < 2) {
        esLocations.value = [];
        return;
      }

      try {
        esSearchLoading.value.location = true;
        const response = await searchLocationsFromES(val);
        if (response && response.code === 200 && response.data) {
          // 过滤掉已经存在于静态列表中的地点
          const staticLocationList = state.locationOptions;
          esLocations.value = response.data.filter(location => !staticLocationList.includes(location));
        } else {
          esLocations.value = [];
        }
      } catch (error) {
        esLocations.value = [];
      } finally {
        esSearchLoading.value.location = false;
      }
    }, 500);

    return {
      // 明确展开state的所有属性
      loading: state.loading,
      contactsList: state.contactsList,
      allContacts: state.allContacts,
      // 使用计算属性确保total始终为响应式的最新值
      total: computed(() => state.total),
      searchTimeout: state.searchTimeout,
      queryParams: state.queryParams,
      selectedIds: state.selectedIds,
      detailsVisible: state.detailsVisible,
      currentContact: state.currentContact,
      addToLeadsVisible: state.addToLeadsVisible,
      leadForm: state.leadForm,
      expanded: state.expanded,
      filters: state.filters,
      checkAll: state.checkAll,
      isIndeterminate: state.isIndeterminate,
      filterOptions: state.filterOptions,
      // companyFoundedMode: state.companyFoundedMode, // 临时注释掉公司成立时间筛选功能
      // exactYearInput: state.exactYearInput,
      // exactYears: state.exactYears,
      // rangeStartYear: state.rangeStartYear,
      rangeEndYear: state.rangeEndYear,
      jobTitleOptions: state.jobTitleOptions,
      industryOptions: state.industryOptions,
      locationOptions: state.locationOptions,
      companyNameOptions: state.companyNameOptions,
      companySizeOptions: state.companySizeOptions,
      salaryOptions: state.salaryOptions,
      jobTitleSearch,
      industrySearch,
      locationSearch,
      companyNameSearch,
      filteredJobTitles,
      filteredIndustries,
      filteredLocations,
      filteredCompanyNames,
      filteredContacts,
      paginatedContacts,
      totalPages,
      jumpPage,
      handleSearch,
      handleNameSearch,
      handleNameInputChange,
      resetNameSearch,
      handleSelectionChange,
      showDetails,
      toggleContactDetails,
      handleAddToLeads,
      submitAddToLeads,
      handleExport,
      handlePrev,
      handleNext,
      handleJumpPage,
      handleSizeChange,
      handleCurrentChange,
      toggleFilter,
      resetAllFilters,
      formatName,
      getRandomAvatar,
      getInitialAvatar,
      getCountryFlag,
      handleSingleSelection,
      formatCountryName,
      handleCheckAllChange,
      handleFilterChange, // 添加handleFilterChange函数
      updateCheckAllStatus,
      initAllFilters,
      Search,
      formatPhoneNumber,
      formatEmail,
      hasExtraFields,
      extraFields,
      hasFilteredExtraFields,
      filteredExtraFields,
      formatFieldName,
      getCompanySizeLabel,
      getCompanySizeChineseLabel,
      getJobTitleLabel,
      getJobTitleChineseLabel,
      getIndustryLabel,
      getIndustryChineseLabel,
      getLocationLabel,
      getLocationChineseLabel,
      getCompanyNameLabel,
      getCompanyNameChineseLabel,
      getSalaryLabel,
      transformFilterToI18nArray,
      buildI18nFilterParams,
      // testI18nFunctions,
      validateContactData,
      matchesSearch,
      getExtraFields,
      getFilteredExtraFields,
      handleAvatarError,
      handleFlagError,
      searchByKeyword,
      isExportCountExceeded,
      isBalanceInsufficient,
      isExportLimitExceeded,
      // 添加导出相关变量
      exportDialogVisible,
      exportCount,
      exportLoading,
      totalMatchCount,
      displayMatchCount,
      userBalance,
      doExport,
      fetchExportCount,
      fetchUserBalance,
      // 临时注释掉公司成立时间筛选相关
      // selectedFoundedYears,
      // foundedYearOptions,
      // handleFoundedYearChange,
      // initFoundedYearOptions,
      // 敏感信息处理
      showFullContactInfo,
      // 符合条件的数量显示
      displayedCount,
      countLoading,
      fetchContactsCount,
      formatNumber,
      // 字段选择相关
      selectedFields,
      allFields,
      currentLanguage,
      initSelectedFields,
      toggleField,
      updateSelectedFields,
      selectAllFields,
      selectNoFields,
      isAllFieldsSelected,
      isNoFieldsSelected,
      // ES查询相关
      esCompanyNames,
      esJobTitles,
      esIndustries,
      esLocations,
      esSearchLoading,
      selectedCustomCompanyNames,
      selectedCustomJobTitles,
      selectedCustomIndustries,
      selectedCustomLocations,
      handleCompanyNameSearch,
      handleJobTitleSearch,
      handleIndustrySearch,
      handleLocationSearch,
      handleCompanyNameItemChange,
      handleJobTitleItemChange,
      handleIndustryItemChange,
      handleLocationItemChange,
      t // 添加t函数到返回值中
    };
  }
});
</script>

<style scoped>
.linkedin-container {
  height: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  width: 100%;
}

.main-container {
  display: flex;
  flex: 1;
  height: 100%;
  min-height: calc(100vh - 60px);
  width: 100%;
}

.content {
  flex: 1;
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
}

.search-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.search-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
  text-align: center;
}

.search-box-container {
  display: flex;
  justify-content: space-between;
  gap: 10px;
  width: 100%;
  max-width: 360px;
}

.search-input {
  flex: 1;
  min-width: 120px;
  font-size: 14px;
}

@media (max-width: 768px) {
  .search-box-container {
    flex-direction: column;
    max-width: 400px;
  }

  .search-input {
    width: 100%;
  }
}

:deep(.el-input__inner) {
  font-size: 16px;
  height: 45px;
  text-align: center;
}

.search-button, .reset-button {
  width: 100%;
  padding: 6px 0;
}

.search-info {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 14px;
  color: #606266;
}

.search-btn-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 主内容区布局 */
.linkedin-main {
  display: flex;
  margin-top: 20px;
  gap: 20px;
  position: relative;
  height: auto;
}

.filter-sidebar-container {
  width: 280px;
  position: sticky;
  top: 20px;
  align-self: flex-start;
  margin-right: 0;
  max-height: calc(100vh - 80px);
}

.filter-sidebar {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 15px 0;
  overflow-y: auto;
  max-height: calc(100vh - 80px);
}

.filter-group {
  padding: 10px 15px;
  border-bottom: 1px solid #f0f2f5;
  position: relative;
}

.filter-header {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 12px 15px;
  justify-content: space-between;
  position: relative;
  border-radius: 6px;
  transition: background-color 0.3s;
  background-color: #f9f9f9;
  margin-bottom: 2px;
}

.filter-header:hover {
  background-color: #f0f2f5;
}

.filter-header span {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.filter-header .el-icon {
  color: #409EFF;
  font-size: 16px;
  transition: transform 0.3s;
}

.filter-content {
  margin-top: 10px;
  padding: 0 10px;
  max-height: 300px;
  overflow-y: auto;
}

.filter-search {
  margin-bottom: 12px;
  position: relative;
}

.filter-search.is-loading .el-input__inner {
  padding-right: 95px; /* 为加载状态文本留出空间 */
}

.filter-search-loading {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  color: #409eff;
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 0 5px;
  border-radius: 3px;
  z-index: 2;
}

.filter-search-loading i {
  margin-right: 5px;
  font-size: 14px;
  animation: rotating 1s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}

/* ES查询结果分隔线 */
.es-result-divider {
  padding: 8px 0;
  margin: 8px 0;
  font-size: 13px;
  color: #409eff;
  font-weight: 500;
  border-top: 1px dashed #e0e0e0;
  border-bottom: 1px dashed #e0e0e0;
  text-align: center;
  background-color: #f5f7fa;
  border-radius: 3px;
}

/* 已选择的自定义项容器 */
.es-selected-items {
  margin-bottom: 12px;
  padding-bottom: 8px;
  background-color: #f0faff;
  border-radius: 4px;
  padding: 5px;
}

.reset-filter-container {
  padding: 10px 15px 15px;
  display: flex;
  justify-content: center;
}

.reset-filter-btn {
  width: 100%;
  margin-bottom: 15px;
  font-size: 14px !important;
  font-weight: 500;
  border-radius: 4px;
  background-color: #f5f7fa;
  color: #606266;
  border: 1px solid #dcdfe6;
}

.reset-filter-btn:hover {
  background-color: #ecf5ff;
  color: #409EFF;
}

/* 调整主图表区域宽度 */
.data-content {
  flex: 1;
  margin-left: 20px;
  width: 100%;
  overflow-x: hidden;
}

/* 添加分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-bottom: 24px;
}

/* 无数据提示样式 */
.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: #909399;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-top: 20px;
}

.no-data i {
  font-size: 64px;
  margin-bottom: 20px;
  color: #DCDFE6;
}

.no-data p {
  font-size: 16px;
  margin: 0;
}

/* 重新设计的卡片式联系人列表样式 */
.contact-card-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 15px;
}

.contact-card {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  position: relative;
  min-height: 120px;
  height: auto;
  border: 1px solid #ebeef5;
  overflow: hidden;
  padding: 0 0 0 10px; /* 增加左侧内边距 */
}

.contact-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 15px;
  min-width: 0;
}

.card-actions {
  width: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-left: 1px solid #f0f2f5;
}

.action-bar {
  background: #fff;
  border-radius: 6px;
  padding: 15px 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.export-btn {
  height: 40px;
  background-color: #409eff;
  color: white;
}

.contact-header {
  display: flex;
  margin-bottom: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #f0f2f5;
}

.contact-name-section {
  display: flex;
  align-items: center;
  width: 100%; /* 确保宽度充满 */
}

.avatar-container {
  margin-right: 15px;
  margin-left: 5px; /* 增加头像左侧边距 */
}

.contact-avatar {
  border-radius: 50%;
  background-color: #1976D2; /* 彩色背景 */
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.name-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.contact-name {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 6px 0;
  color: #303133;
  text-transform: capitalize; /* 姓名首字母大写 */
}

.country-flag-container {
  display: flex;
  align-items: center;
}

.country-flag {
  width: 16px;
  height: 12px;
  margin-right: 5px;
}

.country-name {
  font-size: 13px;
  color: #606266;
}

.info-label, .info-label-compact, .info-label-wide {
  min-width: 80px;
  display: inline-block;
  color: #909399;
  font-size: 13px;
  margin-right: 10px;
  flex-shrink: 0;
  white-space: nowrap;
  text-align: left;
}

.info-row,
.basic-info .info-row,
.basic-info-top .info-row {
  display: flex;
  margin-bottom: 8px;
  align-items: flex-start;
  padding-left: 0; /* 移除内边距，统一对齐 */
}

.info-value {
  flex: 1;
  color: #606266;
  font-size: 13px;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-word;
  white-space: normal;
  text-align: left;
}

.expanded-info {
  margin-top: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 12px;
}

.expanded-info .info-row {
  margin-bottom: 8px;
}

.contact-info {
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
}

.contact-methods {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 8px;
}

.email-info, .phone-info {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #409EFF;
  font-size: 13px;
  background-color: #ecf5ff;
  padding: 4px 8px;
  border-radius: 4px;
}

.category-content {
  padding: 10px;
  max-height: 200px;
  overflow-y: auto;
}

.position-count {
  color: #909399;
  font-size: 12px;
}

.filter-icon {
  display: none; /* 隐藏灰色图标 */
}

/* 联系人详情弹窗样式 */
.contact-detail-dialog :deep(.el-dialog__header) {
  padding: 20px 30px;
  background: linear-gradient(135deg, #1976D2, #0D47A1);
  color: white;
  border-radius: 8px 8px 0 0;
}

.contact-detail-dialog :deep(.el-dialog__title) {
  color: white;
  font-size: 20px;
  font-weight: 600;
}

.contact-detail-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.contact-detail-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: rgba(255, 255, 255, 0.8);
}

.contact-detail-dialog :deep(.el-dialog__headerbtn:hover .el-dialog__close) {
  color: #fff;
}

.contact-resume {
  position: relative;
}

.resume-header {
  padding: 30px;
  display: flex;
  position: relative;
  background: linear-gradient(to bottom, #f8f9fa, #ffffff);
  border-bottom: 1px solid #eaeaea;
}

.resume-avatar {
  margin-right: 25px;
}

.resume-avatar :deep(.el-avatar) {
  border: 3px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.resume-basic {
  flex: 1;
}

.resume-name {
  font-size: 26px;
  margin: 0 0 8px;
  color: #2c3e50;
}

.resume-title {
  font-size: 18px;
  color: #1976D2;
  margin-bottom: 5px;
  font-weight: 500;
}

.resume-company {
  font-size: 16px;
  color: #546E7A;
}

.resume-location {
  margin-left: auto;
  text-align: right;
}

.location-item, .industry-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #78909C;
}

.resume-contact-info,
.resume-work-info,
.resume-skills,
.resume-extra-info {
  padding: 24px 30px;
  border-bottom: 1px solid #eaeaea;
  position: relative;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #37474F;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 18px;
  background-color: #1976D2;
  margin-right: 10px;
  border-radius: 2px;
}

.contact-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.contact-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  border-radius: 8px;
  background-color: #f5f7fa;
  position: relative;
  transition: all 0.3s;
}

.contact-item:hover {
  background-color: #ecf5ff;
}

.contact-item i {
  font-size: 20px;
  color: #1976D2;
}

.item-label {
  font-weight: 500;
  color: #455A64;
  white-space: nowrap;
}

.item-value {
  overflow: hidden;
  position: relative;
}

.work-details {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.work-item {
  margin-bottom: 20px;
}

.company-info {
  margin-bottom: 15px;
}

.company-name {
  font-size: 18px;
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 5px;
}

.company-meta {
  display: flex;
  color: #78909C;
  font-size: 14px;
  flex-wrap: wrap;
  gap: 5px;
}

.company-website {
  margin-top: 5px;
}

.company-website a {
  color: #1976D2;
  text-decoration: none;
  transition: color 0.3s;
}

.company-website a:hover {
  color: #0D47A1;
}

.position-info {
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px dashed #e0e0e0;
}

.position-title {
  font-size: 16px;
  font-weight: 500;
  color: #37474F;
  display: inline;
}

.experience-years, .salary-info {
  display: inline;
  color: #78909C;
  margin-left: 5px;
}

.job-summary {
  position: relative;
  margin-top: 15px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  border-left: 3px solid #1976D2;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.summary-title {
  font-weight: 500;
  color: #455A64;
  margin-bottom: 10px;
}

.summary-content {
  color: #546E7A;
  line-height: 1.6;
}

.skills-content {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.skill-tag {
  margin: 0;
  transition: all 0.3s;
}

.skill-tag:hover {
  background-color: #ecf5ff;
  color: #1976D2;
}

.resume-actions {
  padding: 20px 30px;
  display: flex;
  justify-content: flex-end;
  background-color: #f8f9fa;
}

/* 付费提示横幅 */
.premium-banner {
  padding: 10px 20px;
  background: linear-gradient(135deg, #FFA726, #FB8C00);
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(255, 167, 38, 0.2);
}

.premium-text {
  font-weight: 500;
}

.premium-button {
  background-color: white;
  color: #FB8C00;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.premium-button:hover {
  background-color: #FFF3E0;
}

/* 额外信息样式 */
.extra-details {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
}

.extra-item {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 12px;
  display: flex;
  flex-direction: column;
}

.extra-label {
  font-weight: 500;
  color: #455A64;
  margin-bottom: 5px;
}

.extra-value {
  color: #546E7A;
  word-break: break-word;
}

.info-label-wide {
  min-width: 80px; /* 增加宽度以容纳"领英链接:"等长标签 */
  display: inline-block;
  color: #909399;
  font-size: 13px;
  margin-right: 5px;
  flex-shrink: 0; /* 防止标签被压缩 */
  white-space: nowrap; /* 防止标签换行 */
}

.expanded-info .info-row {
  display: flex;
  margin-bottom: 10px;
  align-items: flex-start; /* 避免文本垂直对齐时重叠 */
}

.info-value {
  flex: 1;
  color: #606266;
  font-size: 13px;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-word; /* 允许长内容在必要时换行而不是溢出 */
  white-space: normal; /* 覆盖之前的nowrap设置 */
}

/* 修复展开信息的样式 */
.expanded-info {
  margin-top: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 15px;
  overflow: hidden; /* 防止内容溢出 */
}

.basic-info-top {
  margin-bottom: 10px;
  padding-bottom: 10px;
}

.basic-info-top .info-row {
  margin-bottom: 5px;
}

.info-label-compact {
  min-width: 80px;
  display: inline-block;
  color: #909399;
  font-size: 13px;
}

/* 临时注释掉公司成立时间筛选样式 */
/* .founded-year-selector {
  margin-bottom: 12px;
}

.founded-year-selector :deep(.el-select) {
  width: 100%;
}

.founded-year-selector :deep(.el-select__tags) {
  max-height: 80px;
  overflow-y: auto;
}

.founded-mode-tabs {
  margin-bottom: 10px;
}

.founded-mode-tabs .el-radio-group {
  width: 100%;
}

.founded-mode-tabs .el-radio-button {
  flex: 1;
} */

/* 敏感信息遮罩样式 */
.masked-info {
  cursor: pointer;
  color: #1976D2;
  text-decoration: none;
  transition: color 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.masked-info:hover {
  color: #0D47A1;
  text-decoration: underline;
}

.info-lock-icon {
  font-size: 12px;
  color: #909399;
  margin-left: 2px;
}

.masked-info:hover .info-lock-icon {
  color: #0D47A1;
}

/* .founded-exact-mode {
  padding: 10px 0;
} */

.exact-input-section {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 8px;
}

.selected-years {
  margin-top: 10px;
}

.selected-years-label {
  font-size: 13px;
  color: #606266;
  margin-bottom: 8px;
}

.years-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

/* .founded-range-mode {
  padding: 10px 0;
} */

.range-input-section {
  margin-bottom: 15px;
}

.range-input-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.range-input-row label {
  font-size: 13px;
  color: #606266;
  min-width: 70px;
}

.custom-range-display {
  margin-top: 10px;
}

.range-display-label {
  font-size: 13px;
  color: #606266;
  margin-bottom: 8px;
}

/* .founded-preset-mode {
  padding: 10px 0;
} */

/* 自定义数字输入框样式 */
.custom-number-input {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  background-color: #fff;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.custom-number-input:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.custom-number-input:hover {
  border-color: #c0c4cc;
}

.custom-number-input:disabled {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
}

.custom-number-input::placeholder {
  color: #c0c4cc;
}

/* 移除数字输入框的默认箭头 */
.custom-number-input::-webkit-outer-spin-button,
.custom-number-input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.custom-number-input[type=number] {
  -moz-appearance: textfield;
}

.contact-methods-inline {
  display: flex;
  flex-wrap: nowrap;
  gap: 15px;
  align-items: center;
}

.contact-methods-inline .email-info,
.contact-methods-inline .phone-info {
  white-space: nowrap;
  display: inline-flex;
  align-items: center;
}

.detail-btn {
  color: #409EFF;
  font-size: 14px;
  font-weight: 500;
  padding: 6px 12px;
  background-color: #ecf5ff;
  border-radius: 4px;
  margin-top: 5px;
}

.detail-btn:hover {
  background-color: #409EFF;
  color: white;
}

/* 导出对话框样式 */
.export-dialog-content {
  padding: 10px 0;
}

.export-info {
  margin-bottom: 20px;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.export-highlight {
  font-weight: bold;
  color: #409eff;
  margin: 0 5px;
}

.export-input {
  margin-bottom: 15px;
}

.export-input p {
  margin-bottom: 10px;
  font-weight: 500;
}

.export-warnings {
  margin-top: 15px;
}

.export-warning {
  color: #f56c6c;
  font-size: 13px;
  margin: 5px 0;
  display: flex;
  align-items: center;
}

.export-warning i {
  margin-right: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.export-note {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

/* 导出限制提示 */
.export-limit-notice {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

/* 字段选择区域样式 */
.field-selection {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 15px;
  background-color: #fafafa;
}

.field-selection-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.field-selection-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  font-weight: 600;
}

.field-selection-actions {
  display: flex;
  gap: 8px;
}

.field-selection-content {
  margin-top: 10px;
}

.field-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 12px;
  margin-bottom: 10px;
}

.field-item {
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.field-item:hover {
  background-color: #f0f9ff;
}

.field-item .el-checkbox {
  width: 100%;
  cursor: pointer;
}

.field-item .el-checkbox__label {
  width: 100%;
  padding-left: 8px;
  cursor: pointer;
}

.field-unselected {
  color: #909399 !important;
  font-weight: normal;
}

.field-warning {
  color: #f56c6c;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
  margin-top: 10px;
  padding: 8px 12px;
  background-color: #fef0f0;
  border: 1px solid #fbc4c4;
  border-radius: 4px;
}

/* 符合条件的数量显示样式 */
.matched-count {
  font-size: 16px;
  color: #606266;
  margin-right: 20px;
  font-weight: 500;
}

.matched-count-number {
  color: #409eff;
  font-weight: bold;
  margin: 0 2px;
}


</style>